How to create constants in JavaScript?

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

image

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
});

view raw

constantsjs.js

hosted with ❤ by GitHub

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.

Read full article on the Infragistics blog

Leave a comment

Create a website or blog at WordPress.com