我最近在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还是反之?


当前回答

对于为什么使用const, Tibos的回答很好。

但是你说:

据我所知,它是用来创建不可变变量的

这是错误的。改变变量不同于重新赋值:

var hello = 'world' // Assigning
hello = 'bonjour!' // Reassigning

使用const,你不能这样做:

const hello = 'world'
hello = 'bonjour!' // Error

但是你可以改变你的变量:

const marks = [92, 83]
marks.push(95)
console.log(marks) // [92, 83, 95] -> the variable has been mutated.

因此,任何不使用=号而改变变量值的进程都是在改变变量。

注:+=例如…重新分配!

var a = 5
a += 2 // Is the same as a = a + 2

所以,底线是: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'指示您的代码标识符将不会被重新分配。

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

个人喜好。你可以使用const,就像你说的,它不会被重新赋值并且是常量。例如,如果你想分配你的生日。你的生日永远不变,所以你可以把它作为一个常数。但你的年龄确实在变化,所以这可能是一个变量。

你的问题有两个方面:使用const而不是var的技术方面是什么,以及这样做与人有关的方面是什么。

技术上的差异是显著的。在编译语言中,常量将在编译时被替换,它的使用将允许其他优化,如删除死代码,以进一步提高代码的运行时效率。最近(使用较少的术语)JavaScript引擎实际上编译JS代码以获得更好的性能,因此使用const关键字将通知它们上述优化是可能的并且应该完成。这将导致更好的性能。

The human-related aspect is about the semantics of the keyword. A variable is a data structure that contains information that is expected to change. A constant is a data structure that contains information that will never change. If there is room for error, var should always be used. However, not all information that never changes in the lifetime of a program needs to be declared with const. If under different circumstances the information should change, use var to indicate that, even if the actual change doesn't appear in your code.