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

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s