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,
- Object for which variable should be created
- Name of the variable to be created
- Object to configure behavior of the variable.