Saturday, July 13, 2013

Is javascript empty array true or false

Not to be accused of plagiarism I would like to point out this stackoverflow link first.

Now, coming to the topic, let me start by asking two questions. In Javascript, what do you think the output will be for the following two code snippets?

1. First code snippet

2. Second code snippet

Before looking at the solutions, take 10 seconds to think what the output might be. Or even better, try them out in the javascript console in your browser (if it is enabled that is).

If you have tried them out, you know the answers. For others, they are below:

1. It would print "empty array is truthy"
2. It would print "empty array == false is true"!!!

That was very confusing to me when I first came to know of it. Then on digging deeper, here's what I found out. Basically, there are two concepts.

First, "if" in javascript would check if the enclosed condition/object is one of the following:
  • false (the false object itself, not just if it is == false, look at the example below)
  • undefined
  • null
  • 0
  • NaN
  • (empty string)
To understand the first bulleted point, a Boolean false object (that is new Boolean(false)) will also evaluate to true in an if condition. Try out the following code: 

For an expression within the "if" condition, remember that the expression will return a value (even if undefined). And "if" operator would work according to that value. If that value is any one in the list above, it would skip the curly brackets code.

Getting back to the first example, an empty array is none of the items in the list above. So it is true. And so javascript would go ahead to evaluate the curly brackets code.

Secondly, the == operator. That would try to convert the array to its string representation by calling the toString method. Why? Take a look at Mozilla javascript reference for comparison opertators.

So, [].toString will evaluate to "" (empty string). Which is equal to false as per the non-strict comparator (==) that we are using. And so in the second example also the code in the curly brackets will be evaluated.

Hope that helps to clarify an empty array seems to act mysteriously.

References: