Replacing let with const

Even when it feels impossible

Charles Stover
3 min readApr 5, 2021

--

In JavaScript, const affords a few benefits:

  1. It lets the team reviewing your code that the value is not going to change, improving confidence.
  2. It throws an error if you attempt to change that variable, preventing accidental re-assignment.
  3. It allows the engine to optimize for unchanging values.
  4. It avoids side effects caused by conflicting changes.
  5. It is more consistent with functional programming and immutable states.
  6. There are instances of better TypeScript inference.

It’s common practice to use const by default, denoting that a variable is constant and unchanging.

However, it can be confusing when you want a constant variable that is conditionally defined, but otherwise unchanging. As an example,

let height = 60;
if (name === 'Charles') {
height = 70;
} else if (
gender === Gender.Male &&
race === Race.White
) {
height = 69;
} else if (gender === Gender.Female) {
height = 64;
}

In the above example, I have conditionally defined the height variable. It starts as let so that I may reassign it immediately to what I want it to constantly be. It’s value will be unchanging going forward, and I…

--

--