1

I know that you can use constants and variables in JavaScript but I'm not really sure what the advantage of using constants is. If you didn't want a variable to change, why would you just not change it? Is there some sort of advantage in how the program runs when using constants instead of variables (maybe it runs faster of something)?

Thank you, I'm just interested as to whether I should be using constants more often.

1 Answers1

1

Three useful things about const:

  • It documents for people reading the code later that the value must not change.
  • It prevents you (or anyone coming after you) from changing the value unless they go back and change the declaration intentionally.
  • It might save the JavaScript engine some analysis in terms of optimization. E.g., you've declared that the value cannot change, so the engine doesn't have to do work to figure out whether the value changes so it can decide whether to optimize based on the value not changing.
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875