let vs. const

Avatar of Chris Coyier
Chris Coyier on

Take your JavaScript to the next level at Frontend Masters.

There are multiple ways to declare variables in JavaScript. We had var, and while that still works like it always has, it is generally said that let and const are replacements to the point we rarely (if ever) need var anymore. This doodle explanation does a pretty good job, if you need a refresher.

What is up for debate is the general coding style of when you should pick one or the other. There are situations where you have to use let, like when you need to redeclare the variable since const doesn’t let you do that. But does that mean you should use const in every single situation where you don’t?

Dan Abramov covers the “controversy”. It’s a very well articulated point and counterpoint of both sides with literal lists that compare the two.

My favorite is the first point on both.

The argument that prefers const when possible:

One Way to Do It: It is mental overhead to have to choose between let and const every time. A rule like “always use const where it works” lets you stop thinking about it and can be enforced by a linter.

The argument that prefers let when possible:

Loss of Intent: If we force const everywhere it can work, we lose the ability to communicate whether it was important for something to not be reassigned.

All five points on both sides are worth a read.

I love Dan’s conclusion: “I don’t care.” This is something that can be linted and auto-fixed. You can have an opinion if you want, just like tabs vs. spaces, but it’s something that automation handles in the day-to-day.

Direct Link →