Modern JS should be written in strict mode which bans implicit globals (preferring to explicitly declare them at the top level instead, thus prevent accidental globals when a variable name is typoed). Yes, you should always use var .
If you use var the variable is declared within the scope you are in (e.g. of the function). If you don’t use var , the variable bubbles up through the layers of scope until it encounters a variable by the given name or the global object (window, if you are doing it in the browser), where it then attaches.
With var it’s still possible as JS when it compiles all scripts it stack declaration of all variables to the very top of the global script, and only assigns value when script triggers the block of code where variable is declared.
Omitting var updates an existing variable. There are two caveats to this: If a variable is already defined in the current scope, prefixing it with var will throw an error. If a variable isn’t currently defined, omitting var creates a new variable (you should always use var to define a new variable, though).
Why VAR is not recommended?
Should I use VAR or let?
The main difference between the two though is that let deals with block scope whereas var deals with global scope or function scope depending on where it’s declared. As long as your variable isn’t declared within any function, var can be used again anywhere else in your code.
Why is var bad JS?
Is var a bad practice?
var speeds up the writing, but may slow down the reading a bit. It’s obviously not a code behaviour rule like “Always initialize variables” because the two alternatives (writing var and writing the type) have exactly the same behaviour. So it’s not a critical rule.
Can I use VAR in Java?
In Java, var can be used only where type inference is desired; it cannot be used where a type is declared explicitly. If val were added, it too could be used only where type inference is used. The use of var or val in Java could not be used to control immutability if the type were declared explicitly.