Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
377 views
in Technique[技术] by (71.8m points)

constants - Why most of the time should I use const instead of let in JavaScript?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Basically,

  • use let if the variable's value will change during the code
  • use const if it won't and you / your team want to use const in those situations in the project you're working on; it's a matter of style

If you do use const, then it's surprising how often it turns out that the guidelines above mean you use const because you end up not needing to change a variable's value (if you're following the usual rules of keeping your functions of reasonable size and such). (Well, it surprised me, anyway...)

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

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

  2. It gives you a nice proactive error if you change the code so it writes to that variable. (A decent IDE can flag this up proactively, but if not, you'll get the error when running the code.) You can then make an informed, intentional decision: Should you change it to let, or did you not mean to change that variable's value in the first place?

  3. 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 code analysis, using const saves it the trouble. (Caveat: I have no idea whether this is actually useful to the JavaScript engine. It seems like it would be, but runtime code optimization is a very complicated and sometimes non-intuitive process.)


1 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."


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...