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 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. It is then very similar to a global variable.
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).
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.
Use ‘let’ and ‘const’ instead of ‘var’
- var uses something called ‘hoisting’, which can lead to unexpected results.
- let and const are both block-scoped. Which means you can declare them in for loop or if statement, and they will only be valid for that block. …
- const prevents variable re-assignment.
Which is better let or VAR?
let can be updated but not re-declared.
This is because both instances are treated as different variables since they have different scopes. This fact makes let a better choice than var . When using let , you don’t have to bother if you have used a name for a variable before as a variable exists only within its scope.
Why you should not use VAR?
What’s the difference between VAR and let?
Is VAR hoisted?
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.
Why did VAR change let?
ES6 introduced two new ways to declare variables, let and const. Both provide better block scoping that var. const differs from let because the immediate value cannot be changed once it is declared.