Recombination of block level variables with var vs. let / const

Part 1

In this example:

var number = 10
{
   var number = 42
}
console.log(number) // 42

Why doesn't line 4 throw away Uncaught SyntaxError: Identifier 'number' has already been declared? It works with let/ constbecause of the block review (although the output, of course, is 10not 42), but how does it work with var?

Part 2

Compare this to the following, which works with var:

var number = 10
var number = 42
console.log(number) // 42

but not with let:

let number = 10
let number = 42 // SyntaxError
console.log(number)

Why vargets a "free pass"? Is this because the property is numberreassigned to the window object when used var?

+4
source share
2 answers

You are allowed to override variables varin JavaScript, even in strict mode .

, var, , , , , . JavaScript, .

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);
Hide result
+6

4 Uncaught SyntaxError: Identifier 'number' has already been declared?

, , var, . . ECMAScript 8.3:

8.3

- , ECMAScript. , , . , .

[...]

ECMAScript , 22.

22: ECMAScript
 Component           Purpose


LexicalEnvironment   Identifies the Lexical Environment used to resolve identifier references made by code within this execution context.
VariableEnvironment  Identifies the Lexical Environment whose EnvironmentRecord holds bindings created by VariableStatements within this execution context.

, JavaScript, "", , , , ​​ , .. , , , LexicalEnvironment VariableEnvironment. "-" , , , . LexicalEnvironment , let const. VariableEnvironment , var.

13.3.2:

13.3.2

    var , VariableEnvironment. Var , undefined . VariableEnvironment BindingIdentifier VariableDeclaration, .

, var . , , VariableEnvironment, var , , VariableEnvironment. number , { … } - , , number . , , :

var number = 10 //declared once
{
  number = 42 //since { … } does not create a new VariableEnvironment, number is the same 
              //variable as the one outside the block. Thus, the two declarations only define
              //number once and every redeclaraction is essentially reassignment.
}
console.log(number) //42

, let const . , { … } .

var " "? , number window var?

, var VariableEnvironment - let const. , ECMAScript var , var , ECMAScript/JavaScript. , let const, , , . , let const , . window, - .

+6

Source: https://habr.com/ru/post/1691524/


All Articles