1. Whether there is variable promotion

Var has a variable boost, let and const do not.

console.log(foo);    // undefined
var foo = 2;

console.log(bar);    / / an error
let bar = 2;

/ / const similarly
Copy the code

Const declares a read-only constant. Once declared, the value of a constant cannot be changed.

What const essentially guarantees is not that the value of a variable cannot be changed, but that the data stored at the memory address to which the variable points cannot be changed. For simple types of data (values, strings, booleans), the value is stored at the memory address that the variable points to and is therefore equivalent to a constant. But for composite types of data (objects, arrays), the variable points to a memory address, and the stored value is just a pointer to the actual data. Const only guarantees that the pointer is fixed (that is, it always points to another fixed address). It has no control over whether the data structure it points to is mutable.

2. Check whether repeated statements are allowed

Var allows repeated declarations. Let and const do not

var a = 1;
var a = 3;

let a = 1;
let a = 3;    / / an error

constlet
Copy the code

3. Whether there is block-level scope

Var has no block-level scope (only functional and global scope) let and const have block-level scope

if (true) {
  var test = true; // Use "var" instead of "let"
}

alert(test); // true
Copy the code
if (true) {
  let test = true; / / the use of "let"
}

alert(test); // Error: test is not defined
Copy the code

The same is true for loops; var declares variables with no block-level scope and no loop local scope

for (var i = 0; i < 10; i++) {
  var one = 1;
  // ...
}

alert(i);   // 10, "I" is still visible after the loop ends. It is a global variable
alert(one); // 1, "one" is still visible after the loop ends. It is a global variable
Copy the code

If a code is inside a function, the variable scope declared by var is the function scope

function sayHi() {
    if(true) {
        var phrase = 'hello';
    }
    alert(phrase)    // hello
}
sayHi();
alert(phrase)    // phrase is not defined
Copy the code