Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 465
Mohammed Saimon Avatar asked Dec 11 '16 13:12

Mohammed Saimon


People also ask

Why you should always use const?

The argument that prefers const when possible: One Way to Do It: It is mental overhead to have to choose between let and const every time. A rule like “always use const where it works” lets you stop thinking about it and can be enforced by a linter.

Is const faster than let JavaScript?

The execution context underlying how the JavaScript interpreter runs the code is basically the same when you use var compared to when you use let and const . That results in the same execution speed.

Why should you use const in JavaScript?

const prevents the variable to be assigned to another value. We could say it makes the pointer immutable, but it doesn't make the value immutable too!

Is Let better than const?

Hoisting of const var variables can be updated and re-declared within its scope; let variables can be updated but not re-declared; const variables can neither be updated nor re-declared. They are all hoisted to the top of their scope.


2 Answers

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's¹ 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.)


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

like image 192
T.J. Crowder Avatar answered Oct 20 '22 11:10

T.J. Crowder


Using const by default is essentially a matter of programming style. However there are pros and cons to each:

Arguments in favor of using const by default

The arguments in favor of using const by default are the following:

  1. It avoids side effects caused by involuntary reassignments;
  2. During a code review, it removes an uncertainty, because the developer who sees a const variable can count on the certainty that it will not be reassigned;
  3. Maybe we could say it is more consistant with functional programming and immutable states.
  4. With TypeScript, there are some cases with better inferences.

Here is an example of advantage when using const with TypeScript:

const hello = "Hello" as string | undefined if (hello !== undefined) {     ["A", "B"].forEach(         name => console.log(`${hello.toUpperCase()}, ${name}`) // OK     ) } 

With let, in strict mode, TypeScript detects an error:

let hello = // … // …         name => console.log(`${hello.toUpperCase()}, ${name}`) //                             ^__ error here: Object is possibly 'undefined'. 

Arguments in favor of using let by default

I summarize here the article Use “let” by default, not “const” that gives arguments in favor of using let by default rather than const:

  1. Re-assignment is not a dangerous thing, it is just... usual;
  2. If a variable could be reassigned, then it should be declared with let, because it is more expressive to reserve const for real constants;
  3. const is misleading because it doesn’t stop references being modified;
  4. It is two more characters to write and to bundle;
  5. Using const by default is inconsistant with function parameters;
  6. There is no performance gain to use const.
like image 27
Paleo Avatar answered Oct 20 '22 11:10

Paleo