Truthy Vs Falsy Values in JavaScript

Introduction

This article describes the truthy and falsy values of JavaScript. What the difference is between them and some exceptions and so on. In simple and short words, it's a boolean type but it's not like true or false only. It's more than that. Understanding them in theory is easy but sometimes leads to big troubles when these values are compared. So let's demystify these values.

Truthy value

JavaScript defines the truthy value. In very short words, any value that is not falsy is a truthy value. Even if you are writing "False" then that is also a truthy value. "0" (zero in quotes) is also a truthy value.

Falsy Value

In JavaScript, the following values are considered to be falsy values:

  • false
  • 0
  • null
  • "" (empty string)
  • NaN (Not a Number)
  • #ff0000

All other values of JavaScript can be safely assumed to be truthy values. Even an empty function, empty array and empty objects are also truthy.

Comparing Falsy and Truthy values

The need for learning these values is because of its use in comparison. The comparison is where these values creates many troubles. Misinterpretation of any value may lead to the wrong action in a script. Therefore it is necessary to check for truthy and falsy values correctly.

The Falsy values 0, "" (empty string) and false are equal to each other and comparison among them results in a true value.

 
 
Null and undefined are both falsy values but are not equal to any value, not even falsy. A bit strange but that's true.


 

 

Null and undefined are equal to themselves.



And the last one that is superior or a VVIN number in JavaScript is the number that is Not a Number! Yes! it's none other then NaN. This Mr. is not equal to any one, not even to his duplicate (Other NaN). Any comparison made with NaN will lead the result to false and the entire script is ruined.



Now the question is, how to check for this very, very important number. To save us from this NaN devil JavaScript provides the isNaN() function. This function can handle the expressions returning NaN.


 


 

Using "==="

To avoid the logical error in a script you can use triple equal (===) or triple not equal(!==). Unlike a double equal (==) that uses a value for the equality check, triple equal (===) checks on the basis of value and type.


 


 

 

Summary

From the preceding article I can suggest that you always use a triple equal since it is difficult to memorize the rules of double equal and truthy falsy comparison results. Thanks for reading this article. Don't forget to share and comment.

Up Next
    Ebook Download
    View all
    Learn
    View all