Differences between various declared variables
Declare a variable
+ var & function ES5 + Let & Const & Class & Import ES6No variable promotionCopy the code
Let and Const
The VO/AO variable object is stored in the current context. The pointer between the ** variable ** and the ** value ** can be changed later on request. Const does not allow changing the pointer to the + const declarationCopy the code
/*Let change the pointer variable to */
let a =12;
a = 13;
console.log(a); / / = > 13
/ * - * /
/*const cannot change the pointer to */
const a = 12;
a = 13;
console.log(a); //=>Uncaught TypeError: Assignment to constant variable
/*cosnt*/
const obj = {
name:'jake'
}
obj.name = 'yzl';
console.log(obj.name); //=>yzl
/ * - * /
const obj; //=>Uncaught SyntaxError: Missing initializer in const declaration
/ * - * /
const fn = function (){}; // Function expression (there is no variable promotion, can only be used after creating a function); Const fn cannot be refactored later [recommended];
Copy the code
Let/Const vs. Var
- Variable ascension
- Repeat statement
- The relationship with GO
- Block-level scope
- Temporary dead zone
- .
Let vs Var
Variable ascension
/* var can be variable promoted. Let cannot be variable promoted
console.log(a); //=>undefined
console.log(b); //=>Cannot access 'b' before initialization
var a = 1;
let b = 2;
Copy the code
Repeat statement
/* const const const; /* const; /* const; /* const; /* const; /* const; /* const The browser bottom from the server side to get JS code (now are string) 2. The first lexical parsing (according to ECMA262), analysis completed to generate an AST syntax tree! ! 3. The bottom layer of the browser (such as C++ programs) then executes the generated syntax tree step by step
/*var*/
var a = 1;
var a = 2;
console.log(a); / / = > 2
/ * - * /
/* The parse let error occurred during the parsing phase, so the code execution console.log(a) cannot be reached at all; Cannot output */
/*let*/
var a = 3;
console.log(a);
let b = 1;
let b = 2;
Copy the code
The relationship with GO
Var /function is defined in GO. Let /const/class is defined in VO/AO
var a = 1;
let b = 2;
console.log(window.a,b); / / = > 1, 2
Copy the code
Block-level scope
/* let b; /* let b; Cannot access 'b' before initialization */
var a = 12;
let b = 13;
if(1= = =1) {console.log(a); / / = > 12
console.log(b); //=>Cannot access 'b' before initialization
var a = 100;
let b = 200;
console.log(a); / / = > 100
console.log(b); / / = > 200
}
console.log(a); / / = > 100
console.log(b); / / = > 13
Copy the code
Temporary dead zone
/* Typeof an undefined variable is undefined */
console.log(typeof(x)); //=>undefined
/ * - * /
/ * analysis: at the time of the lexical analysis found that using the x * / ahead of time
console.log(typeof(x)); //=>undefined
let x = 1; //=>Cannot access 'x' before initialization
Copy the code