JavaScript: true, false, and in between

In JavaScript, all values can be coerced into a Boolean value (i.e. true or false).  Most values will evaluate to true, there are just a handful that will be false.  Aside from the literal false value, the number zero (0), an empty string (''), NaN, null, and undefined all evaluate to false in a Boolean context.  All other values will evaluate to true (even an empty object ({}) or an empty array ([]) or a jQuery selector that didn’t select anything).  So, what contexts cause this Boolean evaluation?  When am I actually going to see this in action?

Most commonly, you’ll see this when using values in an if statement.

var input = $('#text').val(); 
if (input) { // only do this if input is not an empty string } 

So, when you see a non-Boolean value as the condition of an if statement, you can translate that in your head to “if that expression has a value,” so long as you remember that empty objects “have a value,” too.  Pretty easy once you know what you’re seeing.

Now, because all values can act as Booleans, operators that you might expect to return a Boolean result don’t necessarily have to return an explicit Boolean.  As an example:

var text = '';
var index = 10; 
var hasTextOrIndex = text || index;

If the || operator was in the business of returning Boolean values, we might expect hasTextOrIndex to be true; however, while it’s true enough to get us into the body of an if(hasTextOrIndex) statement, the actual value of hasTextOrIndex is 10.  The definition of the || operator is that it returns the left side if it can be converted to true, and otherwise returns the right side (&& returns the left side if it can be converted to false, and otherwise returns the right side).  In the Boolean context, this behaves like the logical operators we’re used to, but lets us use them in non-Boolean ways as well.  Most commonly, you’ll see || used as a null-coalescing operator (like C#’s ??), saying “give me the left side unless it’s undefined, otherwise give me a fallback value.”  Less commonly, you’ll see && used to access an object’s property or method when that object might be undefined (I don’t find it particularly readable, especially with methods, but it’s something you’ll see in the wild, if not something you’ll be using yourself).

jQuery.fn.myPlugin = function (timeout) {
    var timeoutOption = timeout || 500;
	window.console && window.console.log('timeout is ', timeoutOption);
}

The big caution here is to remember that 0, NaN, and '' are falsy values, so you need to be sure that 0 isn’t a valid timeout value if you’re going to use the above example.  Same thing goes with if statements; remember, when you think “has a value” you need to think “isn’t undefined, zero, an empty string, or NaN or null”.

4 Comments

Comments have been disabled for this content.