DEV Community

Aman Kumar
Aman Kumar

Posted on

Understanding Truthy & Falsy Values in JavaScript: The Art of Conditional Logic 🎭

In JavaScript, truthy and falsy values determine how a value behaves in a conditional statement. Some values are automatically considered true, while others are automatically considered false. Knowing how JavaScript handles these values can save time and reduce errors in your code. Let's explore! 🕵️‍♂️


📧 Example 1: Truthy and Falsy in Action

const useremail = "ayushyadavz@gmail.com";

if (useremail) {
    console.log("Got user email");
} else {
    console.log("Don't have user email");
}
// Output: Got user email
Enter fullscreen mode Exit fullscreen mode

Explanation: Here, the string "ayushyadavz@gmail.com" is considered truthy, which means the code inside the if block is executed. If useremail had a falsy value, the else block would run instead.


🎭 What are Falsy Values?

In JavaScript, the following values are falsy, meaning they are treated as false in conditional statements:

  1. false
  2. 0
  3. -0
  4. 0n (BigInt zero)
  5. null
  6. undefined
  7. NaN (Not a Number)

🔍 What are Truthy Values?

Anything not on the falsy list is truthy. This includes:

  • "0" (string)
  • 'false' (string)
  • " " (space character in a string)
  • [] (empty array)
  • {} (empty object)
  • function() {} (any function)

🌟 Example 2: Checking for Empty Arrays & Objects

Sometimes, we need to verify if an array or object is empty. Let's see how to do that.

📝 Checking an Empty Array:

const username = [];

if (username.length === 0) {
    console.log("Array is Empty");
}
// Output: Array is Empty
Enter fullscreen mode Exit fullscreen mode

Explanation: Here, we use the .length property to check if the array username has any elements. If its length is 0, it is considered empty.

🧳 Checking an Empty Object:

const useremailId = {};

if (Object.keys(useremailId).length === 0) {
    console.log("Object is Empty");
}
// Output: Object is Empty
Enter fullscreen mode Exit fullscreen mode

Explanation: In the case of an object, we use Object.keys() to retrieve an array of the object’s keys. If the array length is 0, the object is empty.


🎯 Key Takeaways:

  1. Falsy Values: These include false, 0, null, undefined, NaN, and empty or "falsey" values that JavaScript treats as false.

  2. Truthy Values: Everything else that has a value or type in JavaScript, like "0", "false", [], {}, or functions, are considered truthy.

  3. Empty Check: Use .length to check for empty arrays and Object.keys(obj).length to check for empty objects.


Understanding truthy and falsy values helps you better control your conditional logic and write efficient, error-free code. Ready to level up your JavaScript skills? 🚀

Top comments (2)

Collapse
 
rogemateos profile image
Roge

thank you

Collapse
 
dandoy_jeans_d09ac2524993 profile image
Dandoy Jeans

Thank you sir.