一、var声明的变量在全局范围内有效,let和const只在声明其所在的块级作用域内有效。
if(1) {
let a = 1
var b = 1
console.log(a) //1
}
console.log(a); //a is not defined
if(1) {
let a = 1
var b = 1
console.log(a) //1
}
console.log(b); //1
二、var有变量提升,let和const没有变量提升。
console.log(a); // undefined ===> a已声明还没赋值,默认得到undefined值
var a = 100;
console.log(b); //报错:Cannot access 'b' before initialization ===> 初始化前无法访问'b'
let b = 10;
console.log(c); //报错:Cannot access 'c' before initialization ===> 初始化前无法访问'c'
const c = 10;
三、var允许重复声明同一变量,let和const不允许重复声明同一变量;var和let允许重复赋值同一变量,const在初始化赋值后不能再给这个变量赋值。
const a = 1
const a = 2 //报错: Identifier 'a' has already been declared ===> 'a'已经声明过了
const b //报错:Missing initializer in const declaration ===> 声明常量时未初始化
let c = 2
let d //无报错
c = 7 //无报错
c = 9 //无报错
let c = 3 //报错: Identifier 'c' has already been declared ===> 'c'已经声明过了
var e = 4
var e = 5 //无报错
e = 6 //无报错
e = 7 //无报错
四、const声明一个只读的常量,声明时必须初始化。
const a = 1
a = 2 //报错:Assignment to constant variable ===> 常数变量赋值
const b //报错:Missing initializer in const declaration ===> 在声明常量时未初始化