ECMAScript variables are loosely typed, meaning that variables can be used to hold any type of data. There are three keywords to declare variables: var, const, and let. Var is available in all versions of ECMAScript, while const and let are available only in ECMAScript 6 and later.

The var statement

Var declares scope

The key problem is that a variable defined using the var operator becomes a local variable of the function that contains it. For example, using var to define a variable inside a function means that the variable will be destroyed when the function exits:

function test() {
var message = "hi"; // Local variables
}
test();
console.log(message); / / error! Message is destroyed immediately after the function call
Copy the code

Instead of using the var operator to define variables inside functions, we can create a global variable:

function test() {
message = "hi"; // global variables}
test();
console.log(message); // Message becomes a global variable after the "hi" operator is removed. This variable is defined once the test() function is called and is accessible outside the function.
Copy the code

Var declaration enhancement

The so-called “hoist”, which is to pull all variable declarations to the top of the function scope. The following code does not return an error:

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

The error is not reported because the ECMAScript runtime sees this as equivalent to code like this:

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

In addition, it’s ok to use var to declare the same variable multiple times:

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

Let the statement

Let and VAR have similar functions, but with a very important difference.

The difference between:

  • The scope of the let declaration is block scope, while the scope of the var declaration is function scope. Block scopes are subsets of function scopes, so the same scope restrictions that apply to var also apply to LETS.
if (true) { 
    var name = 'Matt';
    console.log(name); // Matt
}
console.log(name) // 'Matt'


if (true) {
    let age = 26; 
    console.log(age); / / 26
} 
console.log(age); // ReferenceError: age
Copy the code
  • Let does not allow duplicate declarations in the same block scope, which may result in an error.
var name;
var name;

let age;
let age; //SyntaxError; The age identifier is already declared
Copy the code
  • Variables declared by let are not promoted in 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;
Copy the code

PS: The moment of execution prior to the LET declaration is known as the “temporal dead zone”, during which reference to any variable declared later will raise a ReferenceError.

  • Unlike the var keyword, variables declared in the global scope using let do not become properties of the Window object (var declared variables do).
var name = 'Matt'; 
console.log(window.name); // 'Matt'

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

Const statement

Const behaves much the same as let, with the only important differences being that variables declared with it must also be initialized, and attempts to modify a variable declared by const result in a runtime error.

const age = 26;
age = 36; // TypeError: Assigns values to constants
Copy the code

When const says that a value cannot be changed once declared, it really means that the data stored at the memory address to which the variable points cannot be changed

  • Simple types (number, string, Boolean) : Memory addresses are values, i.e. constants.

  • Complex types (objects, arrays, etc.) : An address holds a pointer, and const only guarantees that the pointer is fixed (always pointing to the same address) and that its internal value can be changed.

So as long as you don’t reassign the entire array/object, the push, shift, splice, and other methods on arrays are allowed because they hold a pointer.

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

Finally, to summarize their similarities and differences:

Var and let/const

  1. Block-level scope
  2. There is no variable promotion
  3. Non-repeatable declaration
  4. Global variables declared by lets and const do not hang under the Window object

The const command has two notes:

  • Let can be declared and assigned later. Const must be assigned immediately after being declared or an error will be reported
  • Const Simple types cannot be changed once declared. Pointers to complex types (arrays, objects, etc.) cannot be changed. Internal data can be changed.

Declare style and best practices

  1. Do not use the var

Use let instead of var

  1. Const takes precedence over let

Declare variables using const in preference, and only use let if you know in advance that changes will be made in the future. This allows developers to infer with greater confidence that certain variables will never change in value, and can also quickly detect unexpected behavior due to unexpected assignments.

Reference: juejin. Cn/post / 684490…