DEV Community

Discussion on: Why you shouldn't reassign values in JavaScript

Collapse
 
squgeim profile image
Shreya Dahal

This is what I tell people when they argue against using const ("it's not really immutable"). When using const is the default, we naturally think in ways that result in better code.

Most functions have a structure like this:

let var1;
// ... do stuff to settle on the value for var1

let var2;
// ... do stuff to settle on the value for var2

// ... use var1 and var2 to produce the result.

When we are allowed to reassign, these "concerns" easily get intertwined and a clear separation is not visible. It also becomes harder to extract out meaningful function out for reuse.

With no reassignment the code looks more like:

const var1 = condition ? value1 : value2;

const var2 = (() => {
  // Do stuff to settle on a value of var2

  return value2;
})();

There is a clear separation of concern and it is easier to refactor.