JavaScript Constants And Constant Objects

This is a quick tip about creating constants and constant objects in JavaScript.


Most of you may know that ES6 introduced a way to create constants using const keyword but unfortunately I don’t see it being used widely. Developers are still creating constants using var keyword.

const MY_CONST = 123;

Remember constants created using const keyword have function level scope like variables created with var keyword.

Okay that’s easy peasy. But what about constant objects? Can we create one using const keyword?

const obj = { a: 5 };
obj.b = 10;
console.log(obj); // {a: 5, b: 10}

No it doesn’t create constant objects which make sense because obj contains a reference to some object in memory. So it’s the reference in obj that’s made constant when declared with const keyword. In other words we can’t replace the reference in obj with some other value. Here’s the proof.

// trying to replace above obj with new object
obj = { x: 5 };
console.log(obj); // {a: 5, b: 10}

Constant Objects

So how can we create a constant object in which new properties could not be added, modified or removed? ES5 introduced a feature which allow us to freeze an object. Freezing an object means it’s non-extensible (don’t allow new property additions), non-modifiable, non-removeable, and non-configurable (don’t allow property descriptor modification) properties.

const OBJ = {
  PROP1: 5,
  PROP2: 'str'
// now OBJ is a true constant object
// all below statements will fail
OBJ.PROP1 = 'ifadey';
delete OBJ.PROP2;
Object.defineProperty(OBJ, 'PROP3', { value: 'New Prop' });

You can check if an object is frozen or not using isFrozen method.

Object.isFrozen(OBJ); //true

Many of you may know about this feature but do use it in your projects when creating constant objects.

In addition to freeze method, two other methods were also introduced in ES5 which are not as strict as freeze. They are preventExtensions and seal.

If you found this post useful then don’t forget to subscribe for updates using RSS or Email.

comments powered by Disqus