// 基本类型声明后不能修改const name ='John';
name ='Jane';// TypeError: Assignment to constant variableconst age =25;
age =26;// TypeError: Assignment to constant variableconst isValid =true;
isValid =false;// TypeError: Assignment to constant variable
1.2 引用类型的可变性
// 对象的属性可以修改const person ={name:'John',age:25};
person.name ='Jane';// 正常工作
person.age =26;// 正常工作
person ={};// TypeError: Assignment to constant variable// 数组的元素可以修改const numbers =[1,2,3];
numbers.push(4);// 正常工作
numbers[0]=0;// 正常工作
numbers =[];// TypeError: Assignment to constant variable
2. 声明必须赋值
2.1 正确的声明方式
// ✅ 声明时必须初始化const name ='John';const age =25;const person ={name:'John'};
2.2 错误的声明方式
// ❌ 不能只声明不赋值const name;// SyntaxError: Missing initializer in const declaration// ❌ 不能先声明后赋值const age;
age =25;// SyntaxError: Missing initializer in const declaration
3. 不允许重复定义
3.1 同一作用域重复声明
// ❌ 同一作用域不能重复声明const name ='John';const name ='Jane';// SyntaxError: Identifier 'name' has already been declared// ❌ 与其他声明方式混用也不行const age =25;var age =26;// SyntaxError: Identifier 'age' has already been declaredlet age =26;// SyntaxError: Identifier 'age' has already been declared
3.2 不同作用域的声明
// ✅ 不同作用域可以声明同名常量const x =1;if(true){const x =2;// 正常工作
console.log(x);// 2}
console.log(x);// 1functionexample(){const x =3;// 正常工作
console.log(x);// 3}
4. 不具有变量提升
4.1 变量提升问题
// ❌ 在声明前访问会报错
console.log(name);// ReferenceError: Cannot access 'name' before initializationconst name ='John';// ❌ 在函数中也是一样functionexample(){
console.log(age);// ReferenceError: Cannot access 'age' before initializationconst age =25;}
5. 暂时性死区(TDZ)
5.1 基本概念
// 从作用域开始到变量声明前的区域称为暂时性死区{
console.log(name);// ReferenceError: Cannot access 'name' before initializationconst name ='John';}
5.2 复杂场景中的 TDZ
// 函数参数中的 TDZfunctionexample(x = y, y =1){return[x, y];}example();// ReferenceError: Cannot access 'y' before initialization// 条件语句中的 TDZif(true){
console.log(value);// ReferenceErrorconst value =123;}
6. 不与顶层对象挂钩
6.1 与全局对象的关系
// 浏览器环境const name ='John';
console.log(window.name);// undefined// Node.js 环境const age =25;
console.log(global.age);// undefined