1

I know the difference between const, let, and var:

  • Scope
  • Lack of hoisting
  • The value of const variable cannot be changed.

But why ever use const? Besides from the age old example with PI as 3.14, is there any other advantage then "cleaner code", which I find const is really good for? Is there some efficiency upside to it, because the browser doesn't have to edit the variable?

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
Alex Ironside
  • 4,658
  • 11
  • 59
  • 119
  • 2
    I'll flip that on you - what's the advantage of using `let` if you're not going to change the value? – VLAZ Oct 15 '18 at 18:13
  • 5
    `And the value of const variable cannot be changed` <= didn't you just answer your own question? – Igor Oct 15 '18 at 18:14
  • 2
    You may want to look at this: https://stackoverflow.com/questions/136880/sell-me-on-const-correctness – Jonathan Rys Oct 15 '18 at 18:17
  • 2
    https://stackoverflow.com/questions/38750029/whats-the-point-of-declaring-a-const-in-javascript, https://stackoverflow.com/questions/41086633/why-most-of-the-time-should-i-use-const-instead-of-let-in-javascript, https://stackoverflow.com/questions/48707353/number-is-never-reassigned-use-const-instead-prefer-const, blah blah blah. This is a trivially-researchable question, on SO, and elsewhere. – Dave Newton Oct 15 '18 at 18:18

1 Answers1

2

It's there to help us humans understand the code better and make fewer bugs. By labelling something as const instead of let, you let other developers (including future you) know that it won't be reassigned. And if you accidentally do so, your IDE will tell you there's a problem, thus prompting you to either stop reassigning it, or change it to let to indicate that you really do intend for it to be reassigned.

Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98