var let const的区别
文章目录
let
1. 不可以重复声明
let a = 10;
let a = 20;
//SyntaxError:Identifier 'a' has already been declared
2. 支持块级作用域
if (true) {
let a = 10;
console.log(a);
}
let a = 5;
console.log(a);
// 10 5
3. 不存在变量提升
变量提升:即变量可以在声明之前使用,该值为undefined。
// var 的情况
console.log(v); // undefined
var v = 2;
// let 的情况
console.log(l); // Cannot access 'l' before initialization
let l = 2;
4. 暂时性死区
暂时性死区:在代码块内,使用let命令声明变量之前,该变量都是不可用的
- 使用
let命名变量
x = 'abc'; // ReferenceError
let x;
console.log(x); // undefined
x = 123;
console.log(x); // 123
- 使用
var变量
x = 'abc';
var x;
console.log(x); // abc
x = 123;
console.log(x); // 123
const
定义不可被修改的常量
const a = 5;
a=10;
console.log(a);
// TypeError: Assignment to constant variable.
但是它的值如果是一个引用类型的话,引用对象的属性还是可以改的
const USER = {name:'Tom'};
USER.name= 'Alice';
console.log(USER);
// { name: 'Alice' }
本质:const实际上并不是保证变量的值不能被修改,而是保证变量指向的那个内存地址不能被修改。
扩展知识
经典题
for(var i = 0; i < 5; i++) {
setTimeout(function () {
console.log(i);
});
}
console.log('a');
// a 5 5 5 5 5
for(let i = 0; i < 5; i++) {
console.log(i);
}
console.log('a');
// 0 1 2 3 4 a
涉及到了单线程、任务队列以及事件循环。
由于setTimeout是异步操作, for循环和console.log是同步操作。同步操作进入主线程,异步操作进入任务队列。因此先执行同步操作,等主线程被清空,再执行异步任务。所以会出现先输出a。又因为var是全局作用域的,所以当执行异步操作的时候i的值已经变为5了。输出5 5 5 5 5 。而let支持块级作用域,将接收到每次循环的i值保存了下来。所以输出0 1 2 3 4
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论