Let and const are new additions to ES6 and represent block-level scope, meaning they apply only to the most recent code block.

let:

  • let Declare aA local variable
  • There is no variable promotion, which must be declared before it is used
  • You cannot duplicate declarations in the same code block

const:

  • Const declares a local constant
  • This declaration must be assigned, and the memory address cannot be changed after the assignment, but attribute members can be changed. (when const declares an object, its properties can be modified)
  • It is usually named in uppercase
const NUM = 1;
NUM = 0;/ / an error

// But if you declare an object
const OBJ_STUDENT = {name:'aaa'};
OBJ_STUDENT.name = 'bbb';/ / is not an error
OBJ_STUDENT = {name:'ccc'};/ / an error
Copy the code

Var:

  • Var is a global variable that takes effect in the same function
  • There is variable promotion, that is, using this variable when undeclared prints undefined
console.log(x);//undefined
var x = 'Global variable';

// But let will report an error
console.log(x);//ReferenceError: x is not defined
let x = 'Global variable';
Copy the code