Const, Let, and Var in ES2015
I just completed a freelance project making some bug fixes in a codebase written in ES2015. It was the first time I’d actually worked in ES2015, though I had studied up on it in the past.
So, I’m adding an array to the code that’s going to get modified in a loop, so I do something like this:
And much to my surprise, ESLint barfs up at me that myArray
should be a const
.
But I’m Modifying a const!
So, heading to the Googles, I quickly learn that const
means a value can’t be reassigned, not that it is immutable. const
is not immutable. Slightly unintuitive, but okay.
So, What’s a Body to Do?
That’s easy enough, but it brings up the more interesting question of how should I use const
, let
, and var
in ES2015.
Diving down the internet rabbit hole instead of actually working led me to find a strong preference towards using const
by default and refactoring to let
when necessary while eschewing var
in new code altogether.
That said, Kyle Simpson had a somewhat contrary take on const
, let
, and var
:
Instead, I think the decision steps should generally be:
- Use var for top-level variables that are shared across many (especially larger) scopes.
- Use let for localized variables in smaller scopes.
- Refactor let to const only after some code has been written and you’re reasonably sure that you’ve got a case where there shouldn’t be variable reassignment.
That actually sums up how I intuitively felt about this before I started reading more. I think this is the approach I’ll use in my own code.
Part of me wonders if the preference for the const
-first approach is driven by the fact that it is easier to lint than the approach that Simpson outlines.
Obviously, though, step 1 is follow along with the code you’re working in. The code for my freelance project was const
-first, so I went const
-first. You don’t want to get barfed at by ESLint, after all.