var, let, const difference

ES6 has added let and const characters. Let’s talk about the new differences first:

Scope: The variable declared by let is only valid within the code block where it is located, and there is no variable promotion, that is, the variable can be used before the declaration, and the value is undefined. let throws an error before the variable is declared.

If let and const commands exist within a block, the block's variables declared by those commands form an enclosing scope from the start. Calling it before the declaration will throw an error.

let does not allow the same variable to be declared repeatedly, otherwise an error will be reported.

1, (block scope) Why do you need block scope?
ES5 only has global scope and function scope, no block scope.
Scenario 1: Inner variables override outer variables

var tmp = new Date();

function f() {
  console.log(tmp);
  if (false) {
    var tmp = 'hello world';
  }
}

f();

Scenario 2: The loop variable will leak as a global variable

var s = 'hello' ;

for (var i = 0; i < s.length; i++) {
  console.log(s[i]);
}

console.log(i); // 5

let actually adds block scope to JavaScript, so that the outer scope cannot read the variables of the inner scope.

Variables with the same name in the outer scope can be defined in the inner scope without overwriting the outer variables.

The previous immediate execution function can be directly wrapped with {}.

 

const declares a read-only constant, once declared, it must be initialized immediately, and the value cannot be changed.

If you only declare without assignment, an error will be reported, and the scope is the same as let.

 

There are 6 ways to declare variables in ES6: var, function, let, const, as well as import and class

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325290610&siteId=291194637