Why does var x = x not report an error, let x = x report an error?

// 
var x = x;

// 
let x = x;
// ReferenceError: x is not defined
Feb.17,2022

The essence of the

problem is the JS variable " create create , initialize initialize and assign assign ".

var statement

1. Find all the variables declared with var x , and in this environment "create" these variables
2. Change the variable "initialize" to undefined
3. Start code execution x = x the x variable "assign" to x
Summary:
that is, the var declaration creates the variable and initializes it to undefined before code execution.
this explains why console.log (x) gets undefined before var x = x .

let statement

1. Find all variables declared with let , and "create" variables
2 in this environment. Start executing code (also not initialized )
3. Initialize x to to undefined . (this operation is not a assignment, but only "initialize" )
4. Perform the RHS operation to assign x to x . (this is the assignment operation )
conclusion:
because our initialization statement is the same as the assignment statement, our let xSecretx performs the three and four steps at the same time. But here is a problem, this sentence is wrong. While reporting the error, the third step has been completed, while the fourth step cannot be carried out. While reporting the error, it cancels the initialization of x in the third step. This means that the value has been created as a variable, but not initialized

reference:
https://www.jianshu.com/p/b87.
http://note.codermagefox.com/.


var x is equivalent to
var x undefined;
x x;

var has the feature of variable promotion, while let does not have
let x, when the copied x is not defined

Menu