let
声明变量
- 变量不能重复声明
{ let a = 10; let a = 20; // SyntaxError: Identifier 'a' has already been declared }
- 块级作用域 只在块级作用域内有效
- if else while for { } 都是块级作用域
{ let a = 10; } console.log(a) // ReferenceError: a is not defined // 例如: function testlet() { let a = 30; // 块级作用域 if (true) { let a = 50; console.log(a); // 50 } console.log(a); // 30 } testlet()
- 不存在变量提升
{
console.log(names)
let names = 'zwj'
// ReferenceError: Cannot access 'names' before initialization
}
- 不影响作用域链
{ let names = 'zwj' function fn() { // 函数内部不存在names 向上寻找 console.log(names); } fn() }
const
- 必须赋初始值
const a; // SyntaxError: Missing initializer in const declaration
- 申明常量 值不能修改
const a = 10; const a = 20; // SyntaxError: Identifier 'a' has already been declared
- 存在块级作用域
{ const a = 10 } // 外部无法访问块级作用域内定义的数据 console.log(a); // ReferenceError: a is not defined
- 可以对数组和对象的元素进行修改
// 常量保存的地址没有发生变化 const array = [1, 2, 3, 4, 5] array.push(6) console.log(array); // [ 1, 2, 3, 4, 5, 6 ]