JavaScript  

What are truthy and falsy values in JavaScript?

🚀 Introduction

In JavaScript, values are not always strictly true or false; instead, when used in conditional statements (such as if, while, or ternary operators), values are automatically converted to a Boolean value (true or false). Based on this conversion, they are referred to as truthy or falsy.

✅ What are Truthy Values?

A truthy value is any value in JavaScript that is considered valid when converted to a boolean. Most values in JavaScript are truthy.

Examples of Truthy Values

  
    if ("Hello") {
  console.log("This is truthy"); // Runs because non-empty strings are truthy
}

if (42) {
  console.log("Numbers (except 0) are truthy");
}

if ([]) {
  console.log("Empty arrays are truthy");
}

if ({}) {
  console.log("Empty objects are truthy");
}
  

👉 In short: All values are truthy except the few falsy ones.

❌ What are Falsy Values?

A falsy value is a value that becomes falsy when converted to a Boolean. There are only 7 falsy values in JavaScript.

List of Falsy Values

  • false

  • 0 (the number zero)

  • -0 (negative zero)

  • 0n (BigInt zero)

  • "" (empty string)

  • null

  • undefined

  • NaN

Example

  
    if (0) {
  console.log("Will not run");
} else {
  console.log("0 is falsy");
}

if ("") {
  console.log("Will not run");
} else {
  console.log("Empty string is falsy");
}

if (null) {
  console.log("Will not run");
} else {
  console.log("null is falsy");
}
  

🔄 Implicit Boolean Conversion

JavaScript automatically converts values into a Boolean when they are used in conditions.

  
    console.log(Boolean("JavaScript")); // true (truthy)
console.log(Boolean(0));           // false (falsy)
console.log(Boolean([]));          // true (truthy)
console.log(Boolean(undefined));   // false (falsy)
  

This process is called type coercion.

⚡ Practical Use Cases

  1. Checking for empty values

  
    let username = "";
if (!username) {
  console.log("Please enter a username");
}
  
  1. Short-circuit evaluation

  
    let name = "" || "Guest";
console.log(name); // "Guest"
  
  1. Default values

  
    function greet(msg) {
  msg = msg || "Hello";
  console.log(msg);
}

greet(); // "Hello"
greet("Hi there"); // "Hi there"
  

📝 Summary

In JavaScript, values are classified as truthy or falsy when used in conditions. Truthy values are all values that convert to true (like non-empty strings, numbers other than 0, objects, arrays, etc.). Falsy values are limited to false, 0, -0, 0n, "", null, undefined, and NaN. Understanding this helps developers write clean and bug-free conditional logic.