ES6 — let vs const

Rajesh Naroth
2 min readFeb 5, 2019

--

The established best practice these days is to never use var. Start with const, if you have to reassign the variable, use let.

And I totally agree with it.

const isn’t really const.

We must understand what it means to declare a value as const:

  • const is block scoped.
  • You cannot reassign a value declared as a const.
  • You CAN modify the properties of the value it points to. Defining arrays and objects as const does not protect them from being altered. You have to realize that object variables are actually references. Just as in other languages. Thus immutability only applies to the referenced value not what it points to.
const siteName = 'medium';
siteName = 'google'; // Error
const config = { siteName: 'medium' };
config.siteName = 'google'; // ok
const cities = ['San Jose'];
cities[0] = ['Milpitas']; // ok
cities.push('Sunnyvale'); // ok

In Java, you have the final keyword. In Ruby you may define constants in UPPERCASE. In both cases, it doesn’t stop you from modifying properties referenced by the constant.

const gives you a first level of immutability

It is a small advantage, but is still an advantage. I will use it. Any steps taken to avoid side-effects is worth it.

const protects your function from accidentally being overwritten

function x() {}
x = 0; // No error
x() // x is not a function

In the example above you can see how a function definition can be accidentally overwritten. A function expression can stop this:

const x = function() {};
x = 0; // error

Anonymous functions can be tough to debug. So, you should consider naming it like so:

const x = function x() {};

Also remember:

Your function is not pure if it calls a mutable function

I am not recommending to always use function expressions. Function declarations read well and are also hoisted. As a rule of thumb, you can use function declarations if you need them to be available before you use them. For all others, you can stick to function expressions.

I have watched a video by Kyle Simpson where he suggests that we consider var first, then let and only then consider using const. I love listening to Kyle’s lectures. He is an amazing teacher. He is right all the time except, in this case. :-). One thing that made me think was, he mentions elsewhere that you can never set that value to be garbage collected by saying:

x = null;

Interesting thought. This article by Eric Elliott clears it up.

--

--