Tuesday, May 24, 2011

Falsy JavaScript

In continuation of my previous blog on the basic JavaScript expressions, this blog is about Falsy and Truthy values in JavaScript.

When presented with a non boolean expression instead of a boolean value, JavaScript uses Truthy or Falsy values instead to determine the result. At first glance, this could be confusing and could lead to errors while scripting.

var a = "someval";
var b;
if (a) { // this is a truthy
    // Block is executed
}
if (b) { // b is undefined and so a falsy
    // Block is not executed
}


The Falsy Values
All expressions, objects and values are Truthy by default. There are exceptions and they are called the Falsy values and are listed below:
  # The empty string; ""
  # null
  # undefined
  # The number 0
  # NaN
  # The boolean false

It gets tricky
If you see the below table, you will note that it gets tricky or rather one should be a little extra careful while dealing with Falsy values.

ExpressionValue
Falsy Values
falsefalse
NaNfalse
undefinedfalse
0false
""false
nullfalse
Truthy Values
Infinitytrue
truetrue
1true
"1"true
"0"true
Complicating things now
0+0false
0+"0"true
"0"+"0"true
1-1false
"1"-1false
"1"-"1"false
Double Negation
!!0false
!!1true
!!"0"true
!!"1"true
Logical comparison
null == nulltrue
null == undefinedtrue
null == NaNfalse
null == ""false
null == 0false
null == falsefalse
undefined == undefinedfalse
undefined == NaNfalse
undefined == ""false
undefined == 0false
undefined == falsefalse
NaN == NaNfalse
NaN == ""false
NaN == 0false
NaN == falsefalse
"" == ""true
"" == 0true
"" == falsetrue
0 == 0true
0 == falsetrue
false == falsetrue
Strict Logical comparison
null === nulltrue
"" === ""true
"" === 0false
"" === falsefalse
0 === 0true
0 === falsefalse
false === falsetrue
Arrays
[ ]true
![ ]false
[ ] == truefalse

To remember:
# An empty array evaluates to Truthy whereas any boolean operation on an empty array results in a Falsy
# NaN is not equal to anything, not even itself
# Undefined is not equal to anything, not even itself
# Use strict equals (===) to be extra sure while comparing. This compares by type and value
# Avoid using Falsy value and stick to plain  true or  false to be sure of the results.

Now that you have read this far, Congratulations! I expect 0 bugs from your code henceforth :)

2 comments:

  1. Thanks Chetan, really good post and I love the helpful table showing details of everything.

    Another good one on this topic right here:

    Javascript Falsy

    ReplyDelete
    Replies
    1. thanks for the comment Joe .. and thanks for the link too

      Delete