The front-end ABC series aims to quickly explain the important knowledge points of the front-end and give best practices.

Github Portal, welcome star.

1 ECMAScript variable declarations

ECMAScript has three keywords for declaring variables: var, let, and const. The common format of the three is as follows: [keyword] [identifier] = [value] e.g. Const message = ‘hello’. Where = [value] is optional for var and let, and mandatory for const. If not selected, the variable will be given the default value undefined. Let’s step through the differences between the three variable declarations.

2 var

Variable declarations using the var keyword were the only variable declarations available before ECMAScript 2015. The declared variable behaves differently depending on the scope in which the var statement is declared:

2.1 In function scope

The declared variable becomes a local variable of the containing function and is destroyed immediately after the function is executed (in the absence of a closure), as shown below:

function demo(){
    var message = 'hello'
}

demo()

//ReferenceError: message is not defined
console.log(message)
Copy the code

2.2 In global scope or other block scope

The declared variable becomes a global variable and becomes an attribute of the Window object (browser environment). As follows:

var message = 'hello'

function demo(){
    console.log(message)
}

demo() //hello

Copy the code
if(true){
    var message = 'hello'
}

function demo(){
    console.log(message)
}

demo() //hello

window.alert(window.message) //hello
Copy the code

2.3 Special cases: Omit the var keyword

It is worth noting that the var keyword can be omitted by declaring variables using var, so that the resulting variable becomes a global variable and becomes an attribute of the global object. As follows:

function demo(){
    message = 'hello'
}

demo()

console.log(message) //hello

console.log(globalThis.message) //hello
Copy the code

Where globalThis is the standardized global object. In general, this leads to unexpected global variables and is bad practice. Using var to declare variables has the following characteristics:

  • No error is reported when repeated declarations are made
var message = 'hello'
var message = 'world'
console.log(message) //world
Copy the code
  • There is variable promotion
Log (message); //undefined var message = 'hello'Copy the code

ECMAScript pulls the var variable declaration to the top of the scope at runtime, so the above code is equivalent to

var message //undefined
console.log(message) //undefined
message = 'hello'
Copy the code

3 let

Let and const are new variable naming keywords in ECMAScript 2015. The behavior of naming variables is very different from var.

  • The scope of the let declaration becomes the block scope, meaning that the variable cannot be referenced outside the block
if(true){
    let message = 'hello'
}

//ReferenceError: message is not defined
console.log(message)
Copy the code

As mentioned earlier, variables declared using var in a function scope are local variables and cannot be accessed outside the function scope. However, variables declared with var in if, while, etc., are accessible outside of the statement block because there is no concept of block scope. As follows:

function demo(){
    var message = 'hello'
}

//ReferenceError: message is not defined
console.log(message)
Copy the code
if(true){
    var message = 'hello'
}

console.log(message) //hello
Copy the code


  • An error occurs when making repeated declarations
let message = 'hello'

//SyntaxError: Identifier 'message' has already been declared
let message = 'world'
Copy the code


  • Variables declared by the let in the global scope do not become properties of the global object
let message = 'hello'
console.log(globalThis.message) //undefined
Copy the code


  • There are temporary dead zones


//ReferenceError: Cannot access 'message' before initialization
console.log(message)
let message = 'hello'
Copy the code

In fact, the JavaScript engine notices the variable declared later, but it is an uninitialized state and the engine does not allow any references to the variable until it is declared.

4 const

Const declares variables in much the same way as let, but with two caveats:

  • As stated earlier, a const declaration must also be initialized with an explicit value, otherwise an error will be reported:
//SyntaxError: Missing initializer in const declaration
const message
Copy the code
  • A const declaration usually means that the declared variable is a constant, so modifying its value (the value of the primitive type and the reference to the reference type) raises an error
const message = 'hello'
//TypeError: Assignment to constant variable.
message = 'world'
Copy the code
const message = {a:'hello'}
//TypeError: Assignment to constant variable.
message = {b:'hello'}
Copy the code

Note that if the variable points to a reference type, this restriction only applies to references of the reference type to which the variable points. Modifying the internal properties of this reference type does not raise an error. As follows:

const message = {a:'hello'}
message.b = 'world'
//{ a: 'hello', b: 'world' }
console.log(message)
Copy the code

5 Best Practices

  • Do not use the var

Var declarations of variables behave strangely and can cause problems, so using lets and const is a better choice.

  • Use const in preference

Using const helps the engine find unexpected behavior caused by unexpected assignments. Therefore, let is used only when we know that the value of a variable may change in the future, otherwise const is a better choice.

6 think

What does the following code output? Do you know why?

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