Do you really understand let, const and var?

1.var keyword

To define variables, you can use the var operator (note that var is a keyword), followed by the variable name (i.e. identifier, as described earlier):

var message;

This line of code defines a variable called message that can be used to hold any type of value. (without initialization, it changes to

ECMAScript implements variable initialization, so you can define the variable and set its value at the same time

Value:

var message = "hi";

Here, message is defined as a variable that holds the string value hi. Initializing a variable like this does not identify it as a string

Type is just a simple assignment. Then, you can change not only the saved value, but also the type of value:

var message = "hi";

message = 100; // Legal, but not recommended

In this example, the variable message is first defined as a variable that holds the string value hi, and then rewritten as saved

The value is 100. Although it is not recommended to change the type of variable save value, this is fully effective in ECMAScript.

1. var declaration scope

The key problem is that a variable defined using the VaR operator becomes a local variable of the function containing it. For example, use var

Defining a variable inside a function means that the variable will be destroyed when the function exits:

function test() {

var message = "hi"; // local variable

}

test();

console.log(message); // Error!

Here, the message variable is defined inside the function using var. The function is called test(). Calling it will create this variable and give

It assigns values. The variable is destroyed immediately after the call, so the last line in the example causes an error. However, defining variables within functions saves time

By omitting the var operator, you can create a global variable:

function test() {

message = "hi"; // global variable

}

test();

console.log(message); // "hi"

After removing the previous var operator, message becomes a global variable. As long as the function test() is called once, it will be defined

This variable can be accessed outside the function.

2. Promotion of VaR statement

When using var, the following code will not report an error. This is because variables declared with this keyword will be automatically promoted to the function scope

Top:

function foo() {

console.log(age);

var age = 26;

}

foo(); // undefined

The reason why no error is reported is that ECMAScript runtime regards it as equivalent to the following code:

function foo() {

var age;

console.log(age);

age = 26;

}

foo(); // undefined

This is called "hoist", which is to pull all variable declarations to the top of the function scope. In addition, repeated many times

There is no problem declaring the same variable with var:

function foo() {

var age = 16;

var age = 26;

var age = 36;

console.log(age);

}

foo(); // 36

2.let statement

Let has the same function as var, but there are very important differences. The most obvious difference is that the scope of let declaration is block scope, while the scope of VaR declaration is function scope, and the scope of VaR declaration is function scope.

if (true) {

var name = 'Matt';

console.log(name); // Matt

}

console.log(name); // Matt
let age = 26;

console.log(age); // 26

}

console.log(age); // ReferenceError: age is not defined

Here, the reason why the age variable cannot be referenced outside the if block is because its scope is limited to the inside of the block. Block scope

Is a subset of the scope of the function, so the scope limit applicable to var also applies to let.

let also does not allow redundant declarations in the same block scope. This will result in an error:

var name;

var name;

let age;

let age; // SyntaxErrorï¼› The identifier age has been declared

Of course, the JavaScript engine records the identifier used for variable declaration and its block scope, so nesting uses the same token

The identifier will not report an error because there is no duplicate declaration in the same block:

var name = 'Nicholas';

console.log(name); // 'Nicholas'

if (true) {

var name = 'Matt';

console.log(name); // 'Matt'

}

let age = 30;

console.log(age); // 30

if (true) {

let age = 26;

console.log(age); // 26

}

The redundant declaration and error reporting will not be affected by the mixed use of let and var. These two keywords do not declare variables of different types,

They simply indicate how variables exist in the relevant scope.

var name;

let name; // SyntaxError

let age;

var age; // SyntaxError

1. Temporary dead zone

Another important difference between let and var is that the variables declared by let will not be promoted in the scope.
//name will be promoted

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

//age will not be promoted

console.log(age); // ReferenceError: age is not defined
let age = 26; 

When parsing the code, the JavaScript engine will also pay attention to the let declaration that appears after the block, but before that, it cannot be used in any way
Expression to reference undeclared variables. The moment of execution before the let declaration is called "temporary dead zone", which is here
ReferenceError will be thrown when the stage references any variable declared later.

2. Global declaration

Unlike the var keyword, variables declared in the global scope using let will not become the attributes of window objects (var)

Explicit variables will be).

var name = 'Matt';

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

let age = 26;

console.log(window.age); // undefined

However, the let declaration still occurs in the global scope, and the corresponding variables will continue in the life cycle of the page. Therefore, in order to

To avoid SyntaxError, you must ensure that the page does not declare the same variable repeatedly.

3. Condition statement

When using var to declare variables, the JavaScript engine will automatically put redundant declarations at the top of the scope because the declarations will be promoted

And for a statement. Because the scope of let is a block, it is impossible to check whether a variable with the same name has been declared with let

It is impossible to declare it without declaration.

Using the try/catch statement or the typeof operator cannot solve this problem, because the scope of the let declaration in the condition block is limited to that block.

For this reason, the new ES6 declaration keyword let cannot rely on the conditional declaration pattern.

It's a good thing to note that conditional declarations cannot be made with let s, because conditional declarations are an anti pattern that makes the program more difficult to understand. If you find yourself using this model, there must be a better alternative.

4. let declaration in for loop

Before the let appears, the iteration variables defined by the for loop will penetrate outside the loop body:

for (var i = 0; i < 5; ++i) {

// Circular logic

}

console.log(i); // 5

After changing to let, this problem disappears, because the scope of the iteration variable is limited to the inside of the for loop block:

for (let i = 0; i < 5; ++i) {

// Circular logic

}

console.log(i); // ReferenceError: i not defined

When using var, the most common problem is the peculiar declaration and modification of iteration variables:

for (var i = 0; i < 5; ++i) {

setTimeout(() => console.log(i), 0)

}

// You might think it will output 0, 1, 2, 3, 4

// It actually outputs 5, 5, 5, 5, 5

This is because when exiting the loop, the iteration variable saves the value that causes the loop to exit: 5. Execution timed out after

In logic, all i are the same variable, so the output is the same final value.

When using let to declare iteration variables, the JavaScript engine will declare a new iteration variable for each iteration loop in the background.

Each setTimeout refers to a different variable instance, so console Log outputs our expected value, that is, the following

The value of each iteration variable during loop execution.

for (let i = 0; i < 5; ++i) {

setTimeout(() => console.log(i), 0)

}

// 0, 1, 2, 3, 4 will be output

This behavior of declaring an independent variable instance per iteration applies to all styles of for loops, including for in and for of

Cycle.

3.const statement

const behaves basically the same as let. The only important difference is that when it is used to declare variables, variables must be initialized at the same time, and

Attempting to modify a variable declared by const causes a runtime error.

const age = 26;

age = 36; // TypeError: assign value to constant
// const also does not allow duplicate declarations

const name = 'Matt';

const name = 'Nicholas'; // SyntaxError

// The scope of const declaration is also a block

const name = 'Matt';

if (true) {

const name = 'Nicholas';

}

console.log(name); // Matt

The restriction of const declaration only applies to the reference of the variable it points to. In other words, if the const variable refers to an object,

Then modifying the internal properties of this object does not violate the const restriction.

const person = {};

person.name = 'Matt'; // ok

The JavaScript engine will create separate variable instances for the let declaration in the for loop, although the const variable is different from the let

Quantities are very similar, but you cannot declare iteration variables with const (because iteration variables will increase by themselves):

for (const i = 0; i < 10; ++i) {} // TypeError: assign value to constant

However, if you only want to declare a for loop variable that will not be modified with const, it is also possible. That is, every

This iteration simply creates a new variable. This is particularly relevant for the 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, 5

This article is based on the advanced course of javascript. Reading more books is beneficial and beneficial

Keywords: Vue.js

Added by desmi on Mon, 07 Feb 2022 14:47:14 +0200