The var keyword

1. Var declares scope

Variables defined by var have no concept of blocks and can be accessed across blocks rather than functions

function test() { var message = "hello world"; } test(); console.log(message); / / an errorCopy the code

The variable message is created and assigned a value when the test() function is called, after which the variable is destroyed. Therefore, calling the variable message outside of the function test() returns an error

You can create a global variable by omitting the var operator when defining variables within a function

function test() { message = "hello world"; } test(); console.log(message); // hello worldCopy the code

By omitting the var operator, Message becomes a global variable. This variable is defined once the test() function is called and is accessible outside the function. Global variables defined in local scope are difficult to maintain and are not recommended. In strict mode, assigning a value like this to an undeclared variable causes a ReferenceError to be thrown.

2. The var declaration is improved

Var supports preparsing in JS. The following code will not return an error. This is because variables declared using var are automatically promoted to the top of the function scope:

function foo() {
    console.log(age);
    var age = 26;
}
foo(); // undefined
Copy the code

When code is precompiled, the javaScript engine automatically raises all statements in the var keyword declaration to the top of the current scope, as shown in the following code:

function foo() {
    var age;
    console.log(age);
    age = 26;
}
foo(); // undefined
Copy the code

Let the statement

1. Let declares scope

Variables defined by lets can only be accessed in the block scope, not across blocks or functions, whereas var can be accessed across blocks

If (true) {var name = 'Matt'; console.log(name); // Matt } console.log(name); // Matt // let defined variable if (true) {let age = 26; console.log(age); // 26 } console.log(age); // ReferenceError: Age is not definedCopy the code

Let also does not allow redundant declarations (duplicate declarations) in the same block scope

var name; var name; let age; let age; / / SyntaxError; The age identifier is already declaredCopy the code

2. Temporary dead zones

Another important difference between let and const and var is that variables declared by let and const are not promoted in scope. The new let/const keyword declaration in ES6 generates block-level scope for variables. If a variable is created in the current scope, it cannot be accessed because the syntactic binding has not yet been completed. ReferenceError will be raised if the variable is accessed. Therefore, the time between the execution process entering the scope to create a variable and the variable being accessible is called a temporary dead zone.

// name will be promoted console.log(name); // undefined var name = 'Matt'; // age will not be promoted console.log(age); // ReferenceError: age not defined let age = 26;Copy the code

3. Global declaration

Unlike the var keyword, global variables defined by var are mounted to the Window object and can be accessed using window, whereas variables declared by let in the global scope do not become properties of the Window object

var name = 'Matt';
console.log(window.name); // 'Matt'

let age = 26;
console.log(window.age); // undefined
Copy the code

4. Var and let declarations in the for loop

Iterating variables defined by var in the for loop are filtered out of the loop body:

for (var i = 0; i < 5; ++ I) {// loop logic} console.log(I); / / 5Copy the code

This problem disappears when we use let instead, because the scope of the iteration variable is limited to the inside of the for loop block:

for (let i = 0; i < 5; ++ I) {// loop logic} console.log(I); ReferenceError: I is not definedCopy the code

Use var and let to define variables in the for loop.

for (var i = 0; i < 5; ++ I) {setTimeout(() => console.log(I), 0)} i < 5; ++ I) {setTimeout(() => console.log(I), 0)Copy the code

Let is valid within a code block, and var is valid globally. Let can only be declared once, and var can be declared multiple times.

When the synchronous code is executed, the asynchronous setTimeout code will be executed. When setTimeout is executed, it needs to find a variable I from the current scope. When the for loop is executed, the current I =5, and the output is 5 when setTimeout is executed. The remaining four setTimeout in the task queue are also executed in sequence, with an output of 5.

The variable j is declared with let, and the current I is only valid in this cycle. J in each cycle is actually a new variable, so the j in setTimeout timer is actually a different variable, that is, the final output is 0-4.

Const statement

Const behaves essentially the same as let, with the only important difference:

Const is used to define constants, and must be assigned. Failure to assign results in an error. It is not allowed to be modified after the definition.

const age = 26; age = 36; // Const name = 'Matt'; // Const name = 'Matt'; const name = 'Nicholas'; // SyntaxError // the scope of const declaration is also block const name = 'Matt'; if (true) { const name = 'Nicholas'; } console.log(name); // MattCopy the code

If the variable declared by const is an object, there is no error when modifying properties inside the object.

This is because const declares that the contents of the stack cannot be modified. The value of the basic data type is stored in stack memory, while the reference data type is stored in stack memory. Modifying the attributes of the object does not change the address of the object in stack.

const person = {
    name: 'Lili'
};
person.name = 'Matt'; // ok
Copy the code

The JavaScript engine creates separate instances of variables for let declarations in the for loop. Although const variables are similar to let variables, we cannot use const to declare iterating variables (because iterating variables increment) :

for (const i = 0; i < 10; ++ I) {} // TypeError: Assigns a constantCopy the code

However, if you just want to declare a for loop variable that will not be modified using const, that’s fine. That is, each iteration just creates a new variable. This makes particular sense for for-of and for-in loops:

let i = 0; for (const j = 7; i < 5; ++i) { console.log(j); } // 7, 7, 7, 7, 7 for (const key in {a: 1, b: 2}) { console.log(key); } // a, b for (const value of [1,2,3,4,5]) {console.log(value); } // 1, 2, 3, 4, 5Copy the code

The above content combined with “JavaScript advanced programming (4th edition)” and their own understanding of the written, welcome to discuss together.