JS scope: global scope, function scope. There is no concept of block scope.
Block-level scopes have been added in ES6. The block scope is wrapped in {}, and the {} inside the if and for statements also belong to the block scope.
1. Var has the property of variable promotion. Let and const do not
console.log(a) // undefiend
var a = 10;
/ / equivalent to
var a;
console.log(a); // undefiend
a = 10;
console.log(b) // Error not defined
let b = 10;
console.log(c) // Error not defined
const c = 10;
Copy the code
2. Variables declared by var are mounted to Windows objects, so variables declared by var are global variables, while variables declared by let and const are local variables and cannot be accessed outside the block-level scope
if(true) {
var a = 10;
let b = 10;
const c = 10;
}
console.log(a); / / 10
console.log(b); // b is not defined
console.log(c); // c is not defined
Copy the code
3. Let and const cannot declare variables of the same name in the same scope. Var does
var a = 10;
let b = 10;
const c = 10;
var a = 20;
console.log(a); / / 20
let b = 20; // Error b is declared and cannot be repeated
const c = 20; // Error c already declared cannot be repeated
Copy the code
4. The characteristics of the const
- Cannot be modified after the declaration - must be assigned once the declaration is made - properties can be modified if the declaration is of compound type dataCopy the code
// const a; An error must be assigned
let aa = 10;
aa = 20;
console.log(aa); / / 20
const a = 10;
// a = 20; Error reporting cannot be modified
const arr = ['Yang and Sue'];
arr[0] = 'GAI'
console.log(arr); // ["GAI"]
const obj = {name: 'big and silly'};
obj.name = 'Liu Cong';
obj.age = 38;
console.log(obj); // {name: "liu ", age: 38}
Copy the code