+ 3

What is var? Should I use it or not?

Is it essential to add var to js code every time, or not? I'm asking this question, because my js code is working well, even if I don't add var. And both codes with and without var are showing same results If u understand it, plz explain it to me with examples

19th Jan 2021, 12:12 PM
Anthony
Anthony - avatar
5 Respostas
+ 4
Good observation. Small codes work without var keyword. Without var keyword, variables are added to window as a property, and are all in the global scope. With var keyword, variables are functional scoped. With let keyword, variables are block scoped. When your code grows, you should use keywords to keep variables in their local scope.
19th Jan 2021, 12:23 PM
Gordon
Gordon - avatar
+ 4
丹ⓨㄩک廾 You are welcome ^^ So in JavaScript, we can assign value to variables without the var or let keyword. But that makes the variable global-scoped, even if it initiated in a function, which'll lead to name contamination, and hard-to-debug bugs. Here is a styling guide for JavaScript, by the famous IT corporation AirBnB: https://www.sololearn.com/post/664911/?ref=app https://code.sololearn.com/WKKkpq0efxai/?ref=app
20th Jan 2021, 7:36 AM
Gordon
Gordon - avatar
+ 3
Apparently you didn't catch the point the asker is asking. 丹ⓨㄩک廾 Sagar Maurya Please refer to line 54 to line 74 of the following code : https://code.sololearn.com/WwhKQUoMbXHH/?ref=app And refer to console result. https://www.sololearn.com/post/57512/?ref=app https://code.sololearn.com/Wyr76080kKxS/?ref=app
19th Jan 2021, 4:02 PM
Gordon
Gordon - avatar
+ 1
Yes it necessary without this you can't write ur code properly Check here in easy understanding way https://www.studytonight.com/
19th Jan 2021, 2:23 PM
Sagar Maurya
Sagar Maurya - avatar
+ 1
O I see I got it Gordon sir. Thanks for correcting me. 😌
20th Jan 2021, 2:22 AM
Ayush Kumar
Ayush Kumar - avatar