在ES6中,我们可以使用let关键字声明变量和const关键字声明常量。它们之间的区别如下:
变量可以被重新赋值,而常量则不能。例如:
let x = 1; x = 2; console.log(x); // 输出2 const y = 1; y = 2; // 报错:Assignment to constant variable. console.log(y);
变量在作用域内可以被重新声明,而常量则不能。例如:
let x = 1; let x = 2; // 报错:Identifier 'x' has already been declared console.log(x); const y = 1; const y = 2; // 报错:Identifier 'y' has already been declared console.log(y);
变量声明提升,而常量声明不提升。例如:
console.log(x); // 输出 undefined let x = 1; console.log(y); // 报错:Cannot access 'y' before initialization const y = 1;
在块级作用域内声明的变量,只在该作用域内有效,而在函数作用域内声明的变量在整个函数范围内有效。例如:
{ let x = 1; const y = 2; } console.log(x); // 报错:x is not defined console.log(y); // 报错:y is not defined function test() { var a = 1; let b = 2; const c = 3; } console.log(a); // 报错:a is not defined console.log(b); // 报错:b is not defined console.log(c); // 报错:c is not definedlet关键字用于声明可变的变量,而const关键字用于声明不可变的常量。它们在作用域和声明提升等方面与var关键字不同,应根据需要进行选择。