示例: 使用常量
// program to include constants const a = 5; console.log(a); // constants are block-scoped { const a = 50; console.log(a); } console.log(a); const arr = ['work', 'exercise', 'eat']; console.log(arr); // add elements to arr array arr[3] = 'hello'; console.log(arr); // the following code gives error // changing the value of a throws an error // uncomment to verify // a = 8; // throws an error // const x;
输出
5 50 5 ["work", "exercise", "eat"] ["work", "exercise", "eat", "hello"]
JavaScript ES6 引入了
const
关键字来处理常量。
const
表示对 value 的引用是常量,不能更改。
例如
const a = 5;
a = 44; // throws an error
常量是块范围。因此,块内定义的变量表示与外部不同的值。例如,
{ const a = 50; console.log(a); // 50 } console.log(a); // 5
arr 数组值已更改并添加了新元素。在数组中,可以更改值。但是,不能更改数组引用。例如,
const arr = ['work', 'exercise', 'eat']; arr[3] = 'hello';
另外,常量应该被初始化。你不能只声明一个常量。例如,
const x;
// SyntaxError: const declared variable 'x' must have an initializer.