我最近在JavaScript中遇到了const关键字。据我所知,它是用来创建不可变变量的,我已经测试了,以确保它不能被重新定义(在Node.js中):

const x = 'const';
const x = 'not-const';

// Will give an error: 'constant 'x' has already been defined'

我意识到它还没有在所有浏览器上标准化——但我只对Node.js V8的环境感兴趣,我注意到某些开发人员/项目似乎非常喜欢它,当var关键字可以用于同样的效果时。

什么时候用const代替var比较合适? 它是否应该被用在每一个不存在的变量上 重新分配是声明的? 如果用var来代替,会有什么不同吗 Const还是反之?


当前回答

为了整合前面的答案,除了性能原因外,声明常量变量有一个明显的优势:如果您意外地试图在代码中更改或重新声明它们,程序将分别不更改值或抛出错误。

例如,比较:

// Will output 'SECRET'

const x = 'SECRET'
if (x = 'ANOTHER_SECRET') {  // Warning! Assigning a value variable in an 'if' condition
    console.log (x)
}

:

// Will output 'ANOTHER_SECRET'

var y = 'SECRET'
if (y = 'ANOTHER_SECRET') {
    console.log (y)
}

or

// Will throw TypeError: const 'x' has already been declared

const x = "SECRET"

/* Complex code */

var x = 0

with

// Will reassign y and cause trouble

var y = "SECRET"

/* Complex code */

var y = 0

其他回答

2017年更新

这个答案仍然受到很多关注。值得注意的是,这个答案是在2014年初发布的,从那时起发生了很多变化。Ecmascript-6支持现在是标准。所有现代浏览器现在都支持const,所以使用它应该非常安全,没有任何问题。


2014年原创答案

尽管有相当不错的浏览器支持,但我现在还是避免使用它。来自MDN关于const的文章:

const的当前实现是mozilla特定的扩展,不是ECMAScript 5的一部分。它在Firefox和Chrome (V8)中得到支持。从Safari 5.1.7和Opera 12.00开始,如果在这些浏览器中使用const定义变量,以后仍然可以更改它的值。Internet Explorer 6-10不支持,但Internet Explorer 11支持。const关键字当前在函数作用域中声明常量(就像用var声明变量一样)。

它接着说:

const将由ECMAScript 6定义,但具有不同的语义。与使用let语句声明的变量类似,使用const声明的常量将被块作用域化。

如果你确实使用了const,你将不得不添加一个变通方法来支持稍微老一点的浏览器。

根据我的经验,当我想要设置一些我以后可能想要更改的东西时,我使用const,而不必在代码中寻找已经硬编码的位,例如文件路径或服务器名称。

测试中的错误是另一回事。你试图创建另一个名为x的变量,这将是一个更准确的测试:

const x = 'const';
x = 'not-const';

当涉及到let和const(都是块作用域)之间的决定时,总是首选const,以便在代码中使用清楚。这样,如果您试图重新声明变量,就会得到一个错误。如果没有其他选择,只能重新声明它,只需转换为let。注意,正如Anthony所说,const值不是不可变的(例如,const对象的属性可以发生变化)。

When it comes to var, since ES6 is out, I never used it in production code and can't think of a use case for it. One point that might consider one to use it is JavaScript hoisting - while let and const are not hoisted, var declaration is. Yet, beware that variables declared with var have a function scope, not a block scope («if declared outside any function, they will be globally available throughout the program; if declared within a function, they are only available within the function itself», in HackerRank - Variable Declaration Keywords). You can think of let as the block scoped version of var.

简介:

Const创建一个不可变绑定,这意味着Const变量标识符是不可重赋的。

const a = "value1";

你不能用

a = "value2";

然而,如果const标识符包含一个对象或数组,只要不重新赋值,它的值就可以更改。

const x = { a: 1 }

x.a = 2; // Is possible and allowed

const numbers = [1, 2];
numbers.push(3); // Is possible and allowed

请注意,const是块作用域,就像let一样,它与var不同(var是函数作用域)。

简而言之,当某些东西不太可能通过重赋来改变时,使用const,否则使用let或var,这取决于你想要的作用域。

当可以通过重赋改变什么,不能通过重赋改变什么的时候,对代码进行推理就容易得多了。将const对象更改为let对象非常简单。在默认情况下使用const会让您三思而后行。在很多情况下,这是一件好事。

'const'指示您的代码标识符将不会被重新分配。

这是一篇关于何时使用“const”,“let”或“var”的好文章:JavaScript ES6+: var, let,或const?