Constants in JavaScript

At the time of writing, Javascript doesn’t have a constant feature and many would argue that’s a good thing. However, if you want this functionality then heres a _constant_ function to set an immutable value and retrieve it.

(function() {    
   var consts = {};
   var allowed = {'string': 1, 'number': 1, 'boolean': 1};
   window.constant = function(name, value) {
      var len =  arguments.length;
      if (!len) return consts;
      if (len === 1) return consts[name];
      if (typeof consts[name] != 'undefined') return false;
      if (!, typeof value)) return false;
      consts[name] = value;
      return true;

And here’s how you use it:

//check if defined
typeof constant()['bazinga'] === 'undefined'; //return true if undefined

constant('bazinga', 'Bazinga!')); // returns true
//attempt to redefine
constant('bazinga', 'Bazinga2')); // returns false - constant cannot be redefined

//retrieve value
alert(constant('bazinga')); // Bazinga!
Constants in JavaScript