Replacing let
with const
Even when it feels impossible
3 min readApr 5, 2021
In JavaScript, const
affords a few benefits:
- It lets the team reviewing your code that the value is not going to change, improving confidence.
- It throws an error if you attempt to change that variable, preventing accidental re-assignment.
- It allows the engine to optimize for unchanging values.
- It avoids side effects caused by conflicting changes.
- It is more consistent with functional programming and immutable states.
- 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…