Skip to main content

Command Palette

Search for a command to run...

Why const over let

Is it true that const makes a variable immutable?

Published
2 min read
Why const over let
T

Just a guy who loves to write code and watch anime.

In this article, I want to discuss why I prefer const over let when declaring variables in JavaScript.

Truth about const

Variables declared with const often come across as being immutable. Now, if you have written JavaScript for a while, you know that they aren't immutable, rather, they can't be reassigned.

const arr = [];

// This is valid, because we aren't reassigning the variable, 
// but mutating it instead.
arr.push(1)

// This is NOT valid, because we are reassigning the 
// variable which was declared using const
arr = [22222]

Why const?

If both const and let variables can be mutated/changed, does it really matter which one we pick?

In my opinion, yes it does.

We should stick to const whenever we can, and whenever we need to reassign variables, then we should use let.

Problem with reassignment

Reassignments are wrong, they are a code smell, and they aren't good to write, avoid them whenever you can.

The reason for reassignments being bad goes back to the single responsibility principle.

If a variable is responsible for multiple values, the code gets harder to maintain and the chance for bugs to get introduced is higher.

The mental effort to understand the code when variables have multiple responsibilities is higher, meaning, introducing a higher burden.

This also goes back to the statement that code should be written to be easy to read, not for writing convenience.

Conclusion

This is my take, and some thoughts I've had for a while after seeing people saying it doesn't really matter whether you go with let or const, and some don't even care at all, even if you mix them and things look not so nice, to use nice language here.

Á

This topic is strange to me, probably because, by default, I write const. I don't know why. 😄

There's also a linter rule that fixes all your unnecessary let usages https://eslint.org/docs/latest/rules/prefer-const.

T

Nice Point

1
L

Great article. It makes a point. And always remember, don't use var anymore.

3
T

fosho, the ones ive seen using var in today's age are those that have like 15+ yrs of experience and don't code in JS that often lmao

M
Muphet3y ago

let and const have block scope, var doesn't. there still are cases that you need to pass variables out of blocks

M

Reassignments are wrong, they are a code smell, and they aren't good to write, avoid them whenever you can.

Exactly!

3
T

I had to get it clear haha

let just be confusing stuff, making you think reassignments happen everywhere