I need to understand when to use "var" and when not to

So is “var” needed when i am declaring the variable for the first time? and when i use same variable later i dont need the var keyword?

i tried it out in node console with no result on what happens if i use var keyword all the time with the same variable.

1 Like

var is a keyword which is used to declare a value as variable that once you declare with var it become variable.

as it is a local variable with var keyword.
If you don’t declare with var it become global variable.


For the first question: var is used for declaration of any variable you want to use in your program. This assigns the memory to that variable before execution of code.

For the second question: If you keep declaring your variable each time with var. Then program will take lot of memory because before execution program searches for declarations and assigns memory to variables. So suppose you declared a variable 5 times then it will take 5 time the memory, it would have taken. While there was no need of that.

For more information see this link : https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/var

If you are declaring a variable, ALWAYS use var. If you are using one that you’ve already declared, don’t use var for it again again, or you will redefine it, instead of using what is already there.

If you create a function, and inside that function, just start using a variable without declaring it, Javascript has this weird quirk where it will assume that you meant to declare it as a global variable, and will just create it in the global scope right then and there. You must explicitly declare and define your variables.