What is the meaning of “falsy” in Javascript?
As you probably already know, Javascript has the Boolean values true and false. But, what’s interesting and important is that you understand the fact that everything in Javascript has a built-in Boolean value in addition to it’s ‘obvious’ value, and that Boolean value is known as either falsy or truthy. This may sound confusing, but read on and the concept should become clearer.
Falsy values in Javascript
Here’s a complete list of falsy values in Javascript:
false (the boolean false is also considered falsy) "" (an empty string) 0 (zero) null undefined NaN (a property that represents the "Not-a-Number" value - indicating that a value is not a legal number)
The list above is the complete list of falsy values in Javascript.
Truthy values in Javascript
Now you’re probably wondering about truthy values. Well, every value that’s not in the list above is a truthy value. Even if we take false and put it in quotes – like this: “false” – then that is still a truthy value.
Why falsy values can be dangerous
Suppose we have the following code in an if statement:
if(someString.indexOf('findthis')) ...//do something
The code above checks to see if the ‘findthis’ text is somewhere inside of someString, and if it is it returns the index, which is the position inside someString where the substring ‘findthis’ starts. The problem with this code is the fact that the someString string could very well start with ‘findthis’ (the ‘someString’ string could be something like ‘findthisxzyabc’), which would mean that the indexOf check would return a 0 (because 0 is the position for the very first character in the string). And because 0 is a ‘falsy’ value – meaning that it is treated as a boolean false inside the if statement – then the if statement would evaluate to false even though it should be true in this situation because of the fact that the substring ‘findthis’ was actually found inside someString.
So, you should be very careful when writing your if statements – especially when checking properties that have the potential to return a falsy value. In that situation you should be prepared to handle it appropriately.
Javascript falsy tests:
It’s worth taking some time to go over the different falsy values to test them out and see how they compare to each other.
False, 0, and “” – all falsy values – are considered to be equivalent and can be compared to one another. This is what that would look like:
0 == false //this is true "" == false //this is true 0 == "" //this is also true
However, the values undefined and null are considered to not be equivalent to anything except themselves. So, here is what we would have:
(null == false) // false (null == null) // true (undefined == undefined) // true (undefined == null)// true
And the strange thing about NaN is that it is not considered to be equivalent to anything and that includes itself:
NaN == undefined //false NaN == NaN //false