How to create constants in JavaScript?

Dhananjay Kumar / Monday, December 5, 2016

Constants are immutable variables which value cannot be changed. Once, you have created a constant, its value cannot be changed.

While coding in JavaScript, many times you may have come across a requirement to create constants. Before ECMA Script 6, it was not very easy to create constants in JavaScript. In this post, I will show you to create constants in both ECMA Script 5 and ECMA Script 6.

Constants in ECMA 5

We can create a constant in ECMA Script 5 using Object.defineProperty().  First we need to find out, whether variable would be a global variable or part of the window object.  Once that is determined, create variable by setting writable to false.

Object.defineProperty(typeof global === "object" ? global : window,
	"foo",
	{
	    value: 10000,
	    enumerable: true,
	    configurable: true,
	    writable: false
	});

 Object.defineProperty() function takes three parameters,

  1. Object for which variable should be created
  2. Name of the variable to be created
  3. Object to configure behavior of the variable.

 To create a constant,

  1. As first parameter, we are passing either window object or global object
  2. As second parameter, we are passing name of the variable to be created, which is foo in this case.
  3. As third parameter, we are passing object to configure the variable behavior. Keep in mind to make the writable property to false.

We have created a constant foo. If we try to reassign value of foo, JavaScript will ignore it. However, if we run, JavaScript in strict mode, then JavaScript will throw exception.  Let us see this in action, We are running JavaScript in strict mode and trying to reassign value of foo.

"use strict"
    Object.defineProperty(typeof global === "object" ? global : window,
        "foo",
        {
            value: 10000,
            enumerable: true,
            configurable: true,
            writable: false
        });

    console.log(foo);
    foo = 90;
    console.log(foo);

Due to strict mode, JavaScript will throw exception as shown in the image below:

In this way using the Object.defineProperty() and making writable to false, we can create a constant in ECMA Script 5.

Constants in ECMA 6

As you might have noticed that, creating constants in ECMA Script 5 was not very simple. In ECMA Script 6, new feature const has been introduced. It enables us to create constants or immutable variable.

    const foo = 10000;
    console.log(foo);

If we try to reassign value of foo, JavaScript will complain about it in ECMA Script 6.  Let us try to reassign value of foo as shown in the listing below:

    const foo = 10000; 
    console.log(foo);
    foo= 90; 
    console.log(foo);

JavaScript will complain about this as shown in the image below:

These are two ways constants can be created in JavaScript. I hope you find this post useful. Thanks for reading.