const的基本语法
1.const声明的变量必须赋值,否则会报错
const a = 1;
const b; //SyntaxError: Missing initializer in const declaration
2.const声明的变量的值不能改变
const a = 1;
a = 2; //TypeError: Assignment to constant variable.
3.const和let非常类似,有许多共同点:
(1)不可重复声明同一个变量
const a = 1;
const a = 2; //TypeError: Assignment to constant variable.
(2)不存在变量提升,存在暂时性死区(TDZ),不能在声明前使用
if(true){
console.log(a);
const a = 1; //ReferenceError: Cannot access 'a' before initialization
}
(3)只在其所在的块级作用域内作用
if(true){
const a = 1;
}
console.log(a); //ReferenceError: a is not defined