Turns out you can create constants in JS, as long as your JS engine is ECMAScript 5 compliant (IE >= 9, FF >= 4, Safari >= 5.1.4, Opera >= 12).

Short version

Create an object that you want to have a constant:
var person = {};

Then, instead of using dot notation to add a property, use Object.defineProperty():

        'value': 'Homo sapian'

You now have person.species. However, you can only read it; it can’t be deleted and it won’t be included if you loop over person’s properties.

Long version

Every data property (those created with or Object.defineProperty) of an object has its own properties in turn. These are: value; configurable; enumerable; and writable.

value is the value of the property. configurable means you can change the property, i.e. you can change the property itself, either by changing its properties or by deleting it altogether. enumerable means it turns up when you loop through the object’s properties using for…in. writable means you can change the value of the property (notice the difference between this and configurable, it’s a bit subtle).

So if we want to make a property that acts like a constant, then we want to give it a value and make the other three properties false. Usefully, if we don’t specify values for the properties when we create the new object property, then they default to false. So we just need to give it a value and we get a constant. Conversely if we use the usual form of setting a property: = value;

Then everything is set to true instead. The main caveat is once you’ve set an object property to be not configurable, you’re stuck with it. 

Hat (and everything else) tip to Nicholas Zakas, and “The Principles of Object-Oriented Javascript"

To stay up-to-date with the latest tech news and views, be sure to check out our weekly tech round-up posts - and sign up to our mailing list to have them delivered direct to your inbox.

About the author

Rob Waring

Rob Waring

Rob has been working in web development for the last decade, specialising in front-end technologies. A great believer in the power of Agile development practices, he can often be found shuffling post-its around.

Related content

Tech round-up: Sep 16th

By Steve Anderson

Tech round-up: Mar 11th

By Charlie Afford

We're hiring. Let's talk. View available roles