DEV Community

Cover image for JavaScript Truthy and Falsy Values
Megalraja
Megalraja

Posted on

JavaScript Truthy and Falsy Values

Ever wondered why some values behave like true and others behave like false in JavaScript, even when they aren't actually booleans?

Let's make it simple!

What are Truthy and Falsy Values?

JavaScript evaluates values as either truthy or falsy when they are used in a Boolean context, such as an if condition.

if ("Hello") {
    console.log("This is truthy!");
}
Enter fullscreen mode Exit fullscreen mode

Output:

This is truthy!
Enter fullscreen mode Exit fullscreen mode

Wait, "Hello" isn't true. So why does the condition execute?

Because non-empty strings are truthy in JavaScript!

Truthy Values

These values behave like true in a condition:

if ("JavaScript") console.log("String is truthy");
if (100) console.log("Number is truthy");
if ([]) console.log("Empty array is truthy");
if ({}) console.log("Empty object is truthy");
Enter fullscreen mode Exit fullscreen mode
Yep! Even an empty array [] and an empty object {} are truthy.
Enter fullscreen mode Exit fullscreen mode

Falsy Values

JavaScript has only a few falsy values:

if (false) console.log("Hello");
if (0) console.log("Hello");
if ("") console.log("Hello");
if (null) console.log("Hello");
if (undefined) console.log("Hello");
if (NaN) console.log("Hello");
Enter fullscreen mode Exit fullscreen mode

Nothing gets printed because every condition is falsy.

Other falsy values include -0 and 0n (BigInt zero).

Let's Test Your Understanding!

What do you think this code prints?

let cart = [];

if (cart) {
    console.log("Cart has items!");
} else {
    console.log("Cart is empty!");
}
Enter fullscreen mode Exit fullscreen mode

Answer: Cart has items!

Why? Because an empty array is truthy, even though it contains no elements.

If you want to check whether the cart actually has items, use:

if (cart.length > 0) {
    console.log("Cart has items!");
} else {
    console.log("Cart is empty!");
}
Enter fullscreen mode Exit fullscreen mode

Remember This

Truthy → Behaves like true in a condition.
[] and {} → Truthy!

Falsy → Behaves like false in a condition.
0, "", null, undefined, false, and NaN → Falsy!

Understanding truthy and falsy values helps us write cleaner conditions and avoid unexpected bugs.

Your turn!

What will this print?

console.log(Boolean("0"));
console.log(Boolean("false"));
console.log(Boolean(0));

Drop your answer in the comments before checking it in the console!

Top comments (0)