Given this example:
var number = 10
{
var number = 42
}
console.log(number) // 42
Why does line 4 not throw an Uncaught SyntaxError: Identifier 'number' has already been declared
? It works with let
/ const
because of block scoping (although the output is, of course, 10
not 42
), but how come it works with var
?
Compare this to the following, which works with var
:
var number = 10
var number = 42
console.log(number) // 42
but doesn't with let
:
let number = 10
let number = 42 // SyntaxError
console.log(number)
Why is var
given a "free pass"? Does it have to do with the number
property being reassigned to the window object when var
is used?
You are allowed to redeclare var
variables in JavaScript, even in strict mode.
The scope of a variable declared with
var
is its current execution context, which is either the enclosing function or, for variables declared outside any function, global. If you re-declare a JavaScript variable, it will not lose its value.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting
'use strict'
var someVar = 'Hello';
var someVar = 2 + 2;
console.log(someVar);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With