为什么大多数时候我应该在JavaScript中使用const而不是let? [英] Why most of the time should I use const instead of let in JavaScript?

查看:720
本文介绍了为什么大多数时候我应该在JavaScript中使用const而不是let?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么大多数时候我应该在JavaScript中使用 const 而不是?我们知道如果我们使用 const 那么我们以后就无法重新分配值。那么为什么不使用而不是const?

Why most of the time should I use const instead of let in JavaScript? As we know if we use const then we can't reassign value later. Then why not use let instead of const?

推荐答案

你应该使用让代码中的 const


  • 如果变量的值在代码中发生变化

  • const 如果它不会(但这是一个风格问题,取决于你项目的风格指南)

  • let if the variable's value will change during the code
  • const if it won't (but this is a matter of style subject to your project's style guide)

在实践中,如果你遵循通常的规则来保持你的功能小等等,那么经常会发现这意味着你使用 const 这是多么令人惊讶的事情。 (如果您/您的团队想要)因为您最终不需要更改变量的值。 (好吧,无论如何......这让我感到惊讶)。

In practice, if you're following the usual rules of keeping your functions small and such, it's surprising how often it turns out that that means you use const (if you / your team want to) because you end up not needing to change a variable's value. (Well, it surprised me, anyway...)

使用 const 时变量的¹值无意改变完成了一些事情:

Using const when the variable's¹ value is not meant to change accomplishes a few things:


  1. 它告诉其他人读你的代码你不知道t意图改变这个值。

  1. It tells others reading your code that you don't intend the value to change.

如果你做了一些可以改变变量值而不打算这样做的东西,它会给你一个很好的主动错误。 (智能IDE可以主动标记它。)

It gives you a nice proactive error if you do something that would change the variable's value without having meant to do that. (A smart IDE can flag this up proactively.)

它提示JavaScript引擎的优化器,你不会改变该变量的值。虽然引擎可以经常通过静态代码分析来解决这个问题,但使用 const 可以省去麻烦,并且当静态代码分析可能无法显示值不变时。

It gives a hint to the JavaScript engine's optimizer that you won't be changing that variable's value. While the engine can frequently work that out through static code analysis, using const saves it the trouble, and lets it do that when static code analysis may not reveal that the value is unchanging.

当您收到上述#2中的错误时,您可以做出明智的决定:您是否应该更改它到,或者你不是故意改变那个变量的价值吗?

When you get the error in #2 above, you can then make an intelligent decision: Should you change it to let, or did you not mean to change that variable's value in the first place?

¹是的,使用术语变量来指代根据定义不变的东西很有趣。 :-)规范的术语是绑定,但我打赌你不会听到人们很快就会在日常会话中谈论绑定...所以总体术语可能会保持可变,除非我们可以特别提到作为常数的东西。

¹ Yes, it's funny to use the term "variable" to refer to something that by definition doesn't vary. :-) The specification's term is "binding," but I bet you won't hear people talking about "bindings" in everyday conversation anytime soon... So the aggregate term will probably remain "variable" except when we can specifically refer to something as a "constant."

这篇关于为什么大多数时候我应该在JavaScript中使用const而不是let?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆