43

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?

einpoklum
  • 118,144
  • 57
  • 340
  • 684
Mohammed Saimon
  • 563
  • 1
  • 5
  • 10
  • 2
    Why do you think "_most of the time should I use const instead of let_"? – takendarkk Dec 11 '16 at 13:25
  • i assume this question will be closed, so quick answer, you shouldn't always use any of them, you should use those types as to the need of the variable, const mean that this variable will not be changeable in the app, so if you see this variable you know it will not be changed, and its a constant, let means this will be a general type, that will change in the future. if you need variable that can be changed use var, if not use const. – Yan Mayatskiy Dec 11 '16 at 13:25
  • 4
    `const` (when appropriate) makes it easier for someone to understand your code. By seeing `const` one knows without a look at the rest of the code, that this variable will not get reassigned (although it could still mutate). And, when you don't want reassignment to happen, as a programmer you will get a useful error when it does happen. – trincot Dec 11 '16 at 13:26
  • I've heard from a facebook group but there wasn't the answer why and why not.. @takendarkk – Mohammed Saimon Dec 11 '16 at 13:30
  • In fact, the cases in which you will be needing to use the const keyword are extremely rare. – Bekim Bacaj Dec 27 '16 at 01:29

5 Answers5

63

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

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
39

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.
Paleo
  • 21,831
  • 4
  • 65
  • 76
  • 6
    I appreciate you taking the time to explain things. I actually don't like use `const` for objects that have their properties modified. to me, that defeats the purpose of a something that doesn't change – Kearney Taaffe Oct 16 '20 at 17:27
  • I use let for everything, I haven't done extensive research on it but i've found that in some javascript engines let performs better and have just start defaulting to it – b.stevens.photo Jan 16 '21 at 04:25
  • I learned Kotlin before working with JS and I tend to use `const` first by default because it's in Kotlin's guidelines. Even method parameters are constants by default. You aren't supposed to change those values. – Guilherme Taffarel Bergamin Jul 21 '22 at 13:00
  • 1
    @KearneyTaaffe, the issue is that that isn't even JS specific. If you have a Java or Kotlin or virtually any language's constant, the constant defines that it can't be reassigned, but this doesn't mean you can't change the properties of that constant. I've seen language course teachers getting surprised by it while trying to explain constants in real code, which shows how confusing that concept is. I think language programmers should make constants actually constant. – Guilherme Taffarel Bergamin Jul 21 '22 at 13:01
  • There is no way "There is no performance gain to use `const`" is true, surely knowing a value can't change lets the JavaScript engine perform some optimizations it can't when the value might change. – Boris Verkhovskiy Jun 02 '23 at 23:51
  • Also, using let you save time and keep the flow if you suddenly want to re-assign. – Vidar Jun 10 '23 at 22:01
3

You can use const when you want to declare a non-editable variable.

Meanwhile let is used when you have an editable variable.

It also can be used for variable scoping.

See : let and const


Why we use const most of the time?

Because the const declaration creates a read-only reference to a value (cannot be reassigned).

It prevents us to be confused with the value of the variable.

Community
  • 1
  • 1
Sherly Febrianti
  • 1,097
  • 15
  • 33
0

Using const instead of let has a few benefits:

  • Readability: It signals to other developers that the value of the variable will not be changed once it's assigned. This makes the code easier to read and understand since the reader doesn't have to worry about the value being reassigned somewhere else in the code.

  • Security: When you use const, the value cannot be accidentally or intentionally reassigned. This can help prevent bugs or malicious code from changing the value of the variable.

  • Performance: const can also help the JavaScript engine optimize the code by knowing that the value will not change.

That being said, const should be used only for values that will not change throughout the execution of the program. If you need to reassign a variable later on, you should use let.

Maria Piaredryj
  • 1,584
  • 3
  • 16
  • 35
0

I use var for everything, can't see any benefit to let or const at all, except maybe let in rare cases when it comes to variable naming.

var can be re-assigned and hoisted, which is great if you're using callbacks.

The main reason though is flow:

  • Using the same for everything reduces the cognitive load.
  • Arguably more readable code.
  • And you never have to go back and change your const to a let every time you change your mind about requirements.
  • In the case of const, it's one character more, making your scripts slower and taking longer to type.
  • var can be written with one hand, as opposed to let, but not sure if it's actually faster to type.

If I want something to be read as a constant, I use all caps:

var PI = 3.14

The over use of const is confusing as it's used when things are read only, but not necessarily constants. If I couldn't use var for some reason, I'd just go with let 100%.

Vidar
  • 1,008
  • 14
  • 16