一劳永逸:JavaScript 中的 const 不是不可变的

2025-06-10

一劳永逸:JavaScript 中的 const 不是不可变的

我知道这话已经说了几百遍了,但我仍然看到有人宣称(甚至在一些 JavaScript 书籍中)它const是不可变的。但事实并非如此

JavaScript 中的 const 不是不可变的

在 JavaScript 中,可以使用关键字将值存储在变量中var,这是声明变量最兼容的方式:

var greet = "Hello";
var year = 89;
var not = false;
Enter fullscreen mode Exit fullscreen mode

我之所以说兼容,是因为在 ECMAScript 2015 中我们还有另外两个选项:letconst。老版本的浏览器可能不支持这些新关键字,除非使用像 Babel 这样的“转译器”,否则可能会遇到错误。而在新版本的浏览器中,你可以使用let和 ,const它们在两个方面有所不同var

  • 创建自己的“泡沫”(范围letconst
  • const不能重新分配,也不能重新声明

我所说的“气泡”是指,一个变量声明时,其名称与封闭或外部“气泡”中声明的变量名称重叠let,或者const不重叠。例如:

let name = "John";

{
  let name = "Valentino";
  console.log(name); // "Valentino"
}

console.log(name); // "John"
Enter fullscreen mode Exit fullscreen mode

这里name看起来像是重复的,但实际上它们是两个不同的变量,它们在自己的气泡中。const具有相同的行为:

const name = "John";

{
  const name = "Valentino";
  console.log(name); // "Valentino"
}

console.log(name); // "John"
Enter fullscreen mode Exit fullscreen mode

相同的代码,var但行为方式不同:

var name = "John";

{
  var name = "Valentino";
  console.log(name); // "Valentino"
}

console.log(name); // "Valentino"
Enter fullscreen mode Exit fullscreen mode

正如我所说const,在同一个冒泡中,不能重新赋值或重新声明。如果你尝试重新声明一个const常量,则会报错“SyntaxError: Identifier has already been declared”。如果你将某个值重新赋给同一个常量,则会报错“TypeError: Assignment to constrainedvariables”。以下示例会抛出错误:

const name = "John";
const name = "Valentino";

// SyntaxError: Identifier 'name' has already been declared
Enter fullscreen mode Exit fullscreen mode

并且此代码也会引发:

const name = "John";
name = "Valentino";

// TypeError: Assignment to constant variable.
Enter fullscreen mode Exit fullscreen mode

但请注意,当我们说“const 不能被重新赋值,也不能重新声明”时,这并不意味着const它是不可变的。这是一个几乎每个与我交流过的 JavaScript 开发者都会犯的错误。事实上,任何稍微复杂一点的 JavaScript 数据结构,比如数组或对象,即使赋值给 ,也不仅仅是可变的const

const person = {
  name: "John",
  age: 21
};

person.name = "Valentino";

console.log(person);

// { name: 'Valentino', age: 21 }
// Oh, I wish I was 21 for real!
Enter fullscreen mode Exit fullscreen mode

那怎么是不可变的呢?这是一个数组:

const list = [1, 1, 3, 2, 5];

list.shift();

console.log(list); // [ 1, 3, 2, 5 ]
Enter fullscreen mode Exit fullscreen mode

再说一遍,const 不是 immutable。下次有人说“ const 是不可变的”时,教他几个小技巧。

编码愉快!

鏂囩珷鏉ユ簮锛�https://dev.to/valentinogagliardi/once-and-for-all-const-in-javascript-is-not-immutable-2gop
PREV
和《爱丽丝梦游仙境》一起探索自然语言处理
NEXT
10 reasons to switch from Java to Kotlin right now! 1. Null safety 2. Highlighting the main constructor 3. Initialization and logic of working with DTO classes 4. Explicit declaration of mutable and immutable fields - var/val 5. Collections are immutable by default 6. Extensions. 7. Working with complex classes using primitive methods 8. Possibility of one-line methods really on one line 9. Scope functions 10. Easy to integrate into an existing Java project. Conclusions