Partially inspired by reading up on elm and growing increasingly irritated by a number of vagaries of writing JavaScript functions, I ran an experiment. I was so struck, so surprised by it, that I felt I had to share. Run this in your console:

var x;
var obj = {
  undefined: 'lol, javascript'
};
console.log(obj[x]);

Even in IE8, this echoes out lol, javascript. With a little more experimentation, I quickly found this is a totally legitimate object in JavaScript:

var obj = {
  undefined: 'lol, javascript',
  true: 'yay',
  false: 'nay',
  NaN: 'a free man',
  Infinity: 'whoa',
  null: 'nix'
}

It is valid JavaScript to set an object whose keys are protected values of the language. This has a lot of consequences and reverberations (which I’ll be exploring in upcoming posts) not the least of which is that a simple object can be swapped out for writing logic statements. In the following secToMinSec function, an input of a number of seconds is turned into a humanized string to represent a duration.

function secToMinSec(seconds) {
  output = [];
  var minutes = Math.floor(seconds / 60);
  var remaining = Math.floor(seconds) - (minutes * 60);
  if (minutes !== 0) {
    output.push(minutes + 'm')
  }
  if (remaining !== 0) {
    output.push(remaining + 's')
  }
  if (seconds < 1) {
    output.push('-')
  }
  return output.join(' ');
}

The three conditions can be rewritten like this:

function secToMinSec(seconds) {
  var minutes = Math.floor(seconds / 60);
  var remaining = Math.floor(seconds) - (minutes * 60);
  var minutesCases = {
    true: minutes + 'm',
    false: ''
  };
  var secondsCases = {
    true: remaining + 's',
    false: ''
  };
  var subSecondCases = {
    true:  '-',
    false: ''
  };
  return [
    minutesCases[minutes !== 0],
    secondsCases[remaining !== 0],
    subSecondCases[seconds < 1]
  ].join(' ').trim();
};

Logic statements have been eliminated from this function and replaced by simple object look-ups, where the keys are the conditional evaluations. In the earlier function, it’s implied that nothing would happen if any of those scenarios are false, but using the object syntax, false gets an explicit listing and output. Any case that’s been accounted for is explicitly listed.

That JavaScript objects can house permutations of logic is an opportunity to create a syntax, one that can likely help with legibility and clarify to both author and maintainer what cases have been accounted for. For convenience, I’ll be referring to such structures as ‘case objects’ in subsequent posts.

PostScript: IE8 Compatibility

This technique really only works for IE >= 9. It would need to be considerably modified to work for IE <= 8. IE8 specifically prohibits true and false to be object keys, but does allow them to be members of an array. Array syntax could be made to work, but there would be additional overhead both in terms of authoring such a function and possibly in performance as well.