Recently read JS advanced programming, see the variable part, record it. The content comes from books.

1. Var keyword

function test1(){
    var a = 1;
}
test()
console.log(a)
Copy the code

The above code printed error, cannot access function scope

function test2(){
    a2 = 1;
}
test2()
console.log(a2)
Copy the code

The code above prints 1, because the var operator is omitted, global variables can be created.

function test3(){
    console.log(age);
    var age = 2;
}
test2()
Copy the code

The above code prints undefined because the var operator pulls the variable declaration to the top of the scope, leaving the assignment in place.

2.let

Let can be declared in assignment first, but will not be promoted like Var. A temporary dead zone will be created and ReferenceError will be reported. Such as:

Let name = 'test' {console.log(name) // Uncaught ReferenceError: name is not defined let name = 'code'}Copy the code

Console.log (name) should output the test if there is no variable promotion, but instead raises a ReferenceError indicating that there is a variable promotion in the let, but it has a “temporary dead zone” that does not allow access until the variable is initialized or assigned.

The use of let is most obvious in the for loop, where each loop creates a new block without interfering with each other. The following code and JS advanced program design.

for(let i= 0; i<5; + + I) {setTimeout () = > console. The log (I), 0)} / / 0, 1, 2, 3, 4Copy the code

3.const

Const uses must be declared and assigned, cannot be promoted, and is also a block-level scope. This restriction applies only to the reference to which it points. If you add a const object, you can modify its properties.

conclusion

Var can prompt variables, but declare promotion, assignment left; Const is not promoted, but produces block-level scope that does not allow repeated declarations. Let can be repeatedly assigned, but const cannot. Let is promoted, but has a temporary dead zone and cannot be accessed in advance.

An entry novice, the mistake of the place hope passing big men point out and criticize!