Discussion about this post

User's avatar
Brian Carey's avatar

Not exactly. const and var (now let), describe mutability vs immutability, important for memory efficiency. This is not the same as constant vs variable, which are programmatic concepts.

Constants are variables whose values are set at the beginning of a script. These values are not set programmatically during the execution of a script, nor do they ever change. They allow you to avoid hard coding values in your code by abstracting them as global values. By convention, constants are declared in all capital letters at the beginning of a piece of code. (Often these "constants" are environment variables, with the word variable in their name.) Never-the-less, algorithmically they are constant, and naming them in capital letters reminds programmers never to change them.

On the other hand, there is mutability vs immutability. This is largely irrelevant from a coding perspective, but important for speed and memory. Mutable and immutable objects are handled differently in memory, immutable objects being much more efficient in terms of allocation and access. JS made an unfortunate choice in choosing "const" to declare an object immutable. But JS uses const throughout code for values which are not known at the beginning of code execution, ie. a constant as described above. OTOH, these variables are immutable, and so you get an efficiency gain by declaring them so if you don't need to change them later.

Expand full comment
Mr Yod's avatar

"Variables"

<proceeds to talk about const only...>

Well, no: const, like the name suggests, declares a constant (something that doesn't change), not a variable (something that does).

For variables there's "let" (or the deprecated "var").

Expand full comment
5 more comments...

No posts