Declare a constant, which is the amount by which a value (memory address) cannot change

1. Block-level scope

 if (true) { 
     const a = 10;
 }
console.log(a) // a is not defined
Copy the code

2. A constant must be assigned when declaring it

const PI; // Missing initializer in const declaration
Copy the code

3. After a constant is assigned, its value cannot be modified

const PI = 3.14;
PI = 100; // Assignment to constant variable.

const ary = [100.200];
ary[0] = 'a';
ary[1] = 'b';
console.log(ary); // ['a', 'b']; 
ary = ['a'.'b']; // Assignment to constant variable.
Copy the code

4. Summary

  • The variable declared by const is a constant
  • Since it is a constant and cannot be reassigned, it cannot change the value if it is a basic data type or change the address value if it is a complex data type
  • Const must be declared with a given value

5. Let, const, var

  • The variable declared with var is scoped in the function where the statement is located, and the variable is promoted
  • Variables declared using let are scoped within the block of code in which the statement resides, and there is no variable promotion
  • A const declaration is a constant, the value of which cannot be modified in subsequent code