Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Block-level variable redeclaration with var vs. let/const

Part 1

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?

Part 2

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?

like image 571
Alex Avatar asked Dec 29 '17 20:12

Alex


1 Answers

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);
like image 54
Sébastien Avatar answered Oct 04 '22 21:10

Sébastien