Since all modern browsers started supporting ES6, JavaScript developers have ditched the old var
statement in favour of the newer let
and const
statements. But how do you know which one to use? Here's how to choose between let
and const
in JavaScript.
The catch
You probably already know that the const
statement creates a constant, while the let
statement doesn't. So it seems obvious: use const
for things that won't change, and let
for things that will. What's the catch?
The value of a constant can't be changed through reassignment. This doesn't necessarily mean it's immutable.
Primitive values—such as strings and numbers—are immutable. This means they can't be modified. But objects (and arrays, which are a type of object) are mutable. If you assign an object (or array) to a constant, you can still modify its properties. You just can't reassign the constant with a brand new value.
const name = { first: 'Sam' };
const nums = [ 1, 2, 3, 4, 5 ];
// This is perfectly valid:
name.last = 'Axe';
nums.push(6, 7, 8, 9, 10);
// But you can't do this:
name = { first: 'Chuck', last: 'Finley' };
nums = [ 2, 4, 6, 8, 10 ];
It might seem like hard work to figure out whether you should choose let
or const
, but there's a simple strategy you can use.
A strategy
In my opinion, the best strategy is to default to const
and switch to let
if necessary. This will avoid any unintentional reassignments.
If you use const
but it turns out you need let
, you'll get a TypeError
: 'Assignment to constant variable'. But this is OK; you can just change it. It's also helpful for learning, because over time, you'll remember when you need a constant and when you don't.