Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

ES6 const Is Neither Constant Nor Immutable

DZone 's Guide to

ES6 const Is Neither Constant Nor Immutable

The const keyword in ES6 may not mean what you think it means. Read on to find out more.

· Web Dev Zone ·
Free Resource

I gave a quick talk on JS a while ago on hoisting in JS and while discussing how hoisting applies to variable declarations, we imminently reached ES6’s let and const. We thus began talking about the difference between var, let and const, and how const is not really a constant or immutable.

JavaScript const and Object.freeze()

What Is const?

Constants are block-scoped, much like variables defined using the let statement. The value of a constant cannot change through reassignment, and it can’t be redeclared. - MDN

In reality, const is not really a constant and it’s not immutable.

  const obj = {
    one: 1,
    two: 2
  };

  // Object mutation is ok
  // {one: 1, two: 2, three: 3}
  obj.three = 3;

  // Reassignment doesn't work
  // Uncaught TypeError: Assignment to constant variable.
  obj = {
    one: "bazinga",
    two: "bazinga"
  };

The value of a constant cannot change through reassignment, but any object or array stay mutable.

As an object, an array can be frozen; after doing so, its elements cannot be altered and no elements can be added to or removed from the array. - MDN

  const arr = ["one","two"];

  // Array mutation is ok
  // ["one", "two", "three"]
  arr.push("three");

  Object.freeze(arr);
  // Uncaught TypeError: Cannot add property 3, object is not extensible
  arr.push("new");

Conclusion

In languages like C++, for example, an object is immutable if it’s declared const.

But when it comes to JavaScript, const is not about immutability and to make an object’s values immutable you can use Object.freeze().

You might want to read more on this matter:

Topics:
web dev ,es6 ,javacript ,javascript tutorials ,javascript constants

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}