Contents tagged with Boolean
-
JavaScript: true, false, and in between
In JavaScript, all values can be coerced into a Boolean value (i.e.
true
orfalse
). Most values will evaluate totrue
, there are just a handful that will befalse
. Aside from the literalfalse
value, the number zero (0
), an empty string (''
),NaN
,null
, andundefined
all evaluate tofalse
in a Boolean context. All other values will evaluate to true (even an empty object ({}
) or an empty array ([]
) or ajQuery
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 expecthasTextOrIndex
to betrue
; however, while it’strue
enough to get us into the body of anif(hasTextOrIndex)
statement, the actual value ofhasTextOrIndex
is10
. The definition of the||
operator is that it returns the left side if it can be converted totrue
, and otherwise returns the right side (&&
returns the left side if it can be converted tofalse
, 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’sundefined
, otherwise give me a fallback value.” Less commonly, you’ll see&&
used to access an object’s property or method when that object might beundefined
(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 that0
isn’t a valid timeout value if you’re going to use the above example. Same thing goes withif
statements; remember, when you think “has a value” you need to think “isn’t undefined, zero, an empty string, or NaN or null”.