Let and const declarations

I. Let statement

// Block level area
{
  var value = 10;
  let count = 20;
}
console.log(value); / / 10
console.log(count); // Reference error
Copy the code

Var declarations have variable promotion capabilities and are treated as top-level declarations of scope no matter where they are declared.

Let declaration does not have variable promotion capability, leaving the scope of the block, the variable will immediately become invalid;

console.log(value); //undefined
var value; // Variable promotion leads to logic quirks

console.log(count); // Reference error
let count;
Copy the code

3. If a variable is used before a LET declaration, this area is called a “temporary dead zone”.

if (true) {
  // The dead zone begins
  value = 20;
  console.log(value);
  // End of dead zone
  let value = 10;

  console.log(value);
}
Copy the code

The “temporary dead zone”, abbreviated as TDZ, will also report an error if typeof is used in this area

4. The var declaration can be used repeatedly to declare the same variable, which will replace the previous variable. Let cannot declare a variable repeatedly, even if one of the variables is var.

Const declaration

Const const creates a read-only constant that cannot be changed once declared.

2. Like let declarations, const constants cannot be promoted and have temporary dead zones;

3. Unlike let, const must be assigned immediately or an error will be reported.

Const PI = 3.14;

console.log(PI); // Constants are conventionally capitalized