Custom JavaScript Constants Code Snippet

JavaScript Constants

Although there actually are constants in some environments, e.g. in Firefox you can use const instead of var, in general in JavaScript there are no constants.


To work around that limitation, people often use ALLCAPPS to denote hey, dont touch this var, its meant to be a constant. Its constant-by-convention but the values can be changed by careless programmer on a bad day. If you really want to protect the value, you need to make it private.

PHP-inspired API

In PHP there are the functions define(name, value) to define a constant, defined(name) to check if a constant is defined and constant(name) to get the value of a constants when its name is assembled at runtime and you dont know it a priori. We can do the same in JavaScript. Only, lets not use global functions, but a constant global var and make the functions method of that global. constant.constant(name) is a little mouthful, so lets make that one constant.get(name)


Heres the simple implementation:

This is it. Basically protect an object in a closure and dont provide means to change it, but only to add properties to it.

Theres extra care to check for own properties of the constants private object. This allows to define constants with weird names such as toString and hasOwnProperty. Also only primitive values are allowed to be constants.