
Member-only story
Const, let and var, which and when?
Another article on JavaScript variable assignment 👍
Odds are that you’ve seen the “new” variable assignment keywords const
and let
. They’ve been around a while now 😅
Support for them is good now and if you use a transpiler such as babel
, you’ve likely been using them for some time.
For those in camp TL;DR; If in doubt sort priority of use alphabetically, const
before let
, let
before var
. Prioritise read-only
variables within your code. This reduces the risk of accidental reassignments and unintentional value changes. As a bonus, if you use eslint
, you can use the prefer-const
rule to help you out! ⛑
var
Before transpilers and fancier syntax, there was var
. var
was happy go lucky. You could and still can do whatever you want with it.

Its relaxed nature can lead to issues though if you’re not familiar with how it behaves in certain scenarios.
The problem with var?
There is nothing wrong with using var
. There are no problems with using var
. However, there are some gotchas with using var
.
Lack of block scoping
Variables assigned with the var
keyword have functional scope. This is somewhat intuitive. The variable isn’t accessible outside of the function.

They aren’t block scoped though. That’s where things can get messy 😕 You can reassign variables within a block actually overriding parent assignments. Consider the following;

To clarify, doing this with a function wouldn’t change the value