Thursday, February 20, 2014

Truthiness

A short post today, and remarkably, not one that includes references to the datepicker. No, today's topic is a very common practice in JavaScript - testing the 'truthiness' of an item.

What is testing the truthiness? An example answers that question best. We often see code that's something like this...

foo = bar.name ? bar.name : null;

...which is a fancy way of say "if bar.name then use bar.name else use null" - but do we really know what that means or how it acts? One might assume that if bar.name exists (is not undefined) and if it's not null, it will be returned, otherwise null will be; however, that's not what happens, because the truthiness of any of the following is false and will flow into the else condition of the ternary and return null.

  • an undefined value, e.g., bar = { foo:'not name' };
  • a null value, e.g. bar = { name:null };
  • false, e.g. bar = { name:false }
  • a zero, e.g., bar = { name:0 };
  • an empty string, e.g., bar = { name:'' };

Why does this matter? Let's consider something that's only slightly more complicated but that's closer to a real-world example.

var foo = { name:''; }
  , bar = foo.name ? foo.name : null
  , greet = 'Hello ' + bar
;
console.log(greet);

What will be dumped to the console log? In the good old days, appending a null value to a string made the result null, so our call to console.log would have been the equivalent of console.log(), but regardless of the past, that's not the case now, so we end up with 'Hello null' written to the console log.

The case is not necessarily better if the value is undefined and we reference it anyway, as the following code sends 'Hello undefined' to the console log.

var foo = { snafu:'' }
  , bar = foo.name
  , greet = 'Hello '+bar
;
console.log(greet);

If the property is a boolean, it's acceptable to test it as a boolean, but if it's not a boolean, you probably want to check if it's null or undefined instead and cast the result as the type you want - it's just safer all around.

No comments:

Post a Comment