DEV Community 👩‍💻👨‍💻

Cover image for Truthy and Falsy Values in Javascript
Srijan
Srijan

Posted on • Originally published at hackinbits.com

Truthy and Falsy Values in Javascript

This article was first published on hackinbits.com


When a value is truthy in Javascript, it does not means that the value is equal to true but it means that the value coerces to true when evaluated in a boolean context.

function truthyOrFalsy(value){
  if(value){
    console.log("Truthy Value");
  } else {
    console.log("Falsy Value");
  }
} 
Enter fullscreen mode Exit fullscreen mode

The above function evaluates the passed value in a Boolean Context(if condition) and checks if whether the passed value is truthy or falsy.

Falsy Values

Most of the values in javascript are Truthy, so it is better to list the Falsy value where we have only a limited number of cases. There are a total of 8 falsy values in Javascript:

  • undefined
  • NaN
  • null
  • false
  • "" (Empty String)
  • 0 (0 is an alias for +0)
  • -0
  • 0n (BigInt)

We can validate whether the above values are falsy or not by passing them as a parameter to the truthyOrFalsy function we defined at the starting of this article.

truthyOrFalsy(undefined); // Falsy Value 
truthyOrFalsy(NaN);       // Falsy Value
truthyOrFalsy(null)       // Falsy Value
truthyOrFalsy("");        // Falsy Value
truthyOrFalsy(false)      // Falsy Value
truthyOrFalsy(0);         // Falsy Value
truthyOrFalsy(-0);        // Falsy Value
truthyOrFalsy(0n);        // Falsy Value
Enter fullscreen mode Exit fullscreen mode

Truthy Values

Despite we might think that the empty array( [] ) or empty object( {} )should be falsy values, but they are actually truthy values in Javascript.

truthyOrFalsy([]);  // Truthy Value
truthyOrFalsy({});  // Truthy Value

//some more truthy values

truthyOrFalsy(42);          // Truthy Value
truthyOrFalsy(new Date());  // Truthy Value
truthyOrFalsy(Welcome);   // Truthy Value
Enter fullscreen mode Exit fullscreen mode

I hope this article helped you learn about truthy and falsy values in javascript. Please share your experience in using these in your codebase which may help everyone get some more clarity of the concept.

Top comments (1)

Collapse
 
unip profile image
Abdurrahman Al Hanif

Simple thing that sometimes newbie forget (or not recognize). Also a good reminder for the pro.

Create an Account! The only reason people scroll to the bottom...  
is because they want to read more.

Create an account to bookmark, comment, and react to articles that interest you.