区别:
1、let 和const 有块级作用域。var没有
使用var:
// 使用var 没有块级作用域
function fn() {
var s = 1;
if (s) {
var q = 2;
}
console.log(q); // 2
}
fn()
使用let:
// 使用let
function fn() {
var s = 1;
if (s) {
let q = 2;
}
console.log(q); // Uncaught ReferenceError: q is not defined
}
fn()
2、 let、const存在暂时性死区(Temporal Dead Zone)
暂时性死区的意思也就是说,变量没有声明就不能使用。否则就报错。
console.log(a); // ReferenceError: Cannot access 'a' before initialization
console.log(b); // undefined
let a;
var b;
3、const声明的变量必须赋初始值,也不能进行修改,否则会报错。使用const声明的对象,不允许修改绑定,但是可以修改值。
const a
console.log(a) // Uncaught SyntaxError: Missing initializer in const declaration
const b = 1;
b = 2
console.log(b); // Uncaught TypeError: Assignment to constant variable.
const person = {
name: 'paul',
age: 23,
};
console.log(person) // {name: 'paul', age: 23}
person.age = 24
console.log(person) // {name: 'paul', age: 24}
4、var声明的全局变量会作为全局对象,即window的对象,但是let和const不会
var a = 1
console.log(a === window.a) // true
let b = 2
console.log(b === window.b) // false
5、let和const禁止重声明。var可以。
var a = 3;
var a = 5;
console.log(a); // 5
let a = 8
console.log(a) // Uncaught SyntaxError: Identifier 'a' has already been declared