Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 23

Truthy and Falsy Values in Conditionals

This lesson is built with resources from youtube.com, frontend.turing.edu and 1 more site.

Hello! In our last lesson, we wrapped up our tour of conditional statements by mastering the switch statement, a great tool for handling multiple specific cases for a single value. We concluded by noting that the conditions we write inside our if statements have some powerful, subtle behaviors.

Today, we're diving into one of the most fundamental and practical concepts in JavaScript: truthy and falsy values. Understanding this will allow you to write more concise, professional, and intuitive conditional logic. This is a concept you will use every single day as a developer, especially when working with data in frameworks like Next.js.

By the end of this lesson, you will be able to identify which JavaScript values are "truthy" (behave like true) and "falsy" (behave like false) and use this knowledge to make your conditional code cleaner and more powerful.

What are Truthy and Falsy Values?

So far, we've mostly used explicit booleans (true or false) or comparison expressions (age > 18) in our if statements. However, JavaScript is flexible. When it expects a boolean value but receives something else (like a number or a string), it performs a conversion. This is called implicit type coercion.

Any value in JavaScript can be coerced into a boolean.

  • A value that becomes true is called truthy.
  • A value that becomes false is called falsy.

JavaScript Truthy and Falsy Values - Explained in Detail

To get a great visual introduction to this concept, please watch the first part of this video from Future Fullstack. The creator uses a fantastic analogy of a teacher taking roll call to explain what a 'boolean context' is, and how values can have an inherent 'true' or 'false' nature.

Watch from the beginning until 01:51. Pay close attention to the analogy and the idea that JavaScript automatically converts values.


The Definitive List of Falsy Values

The easiest way to master this concept is not to memorize all the truthy values, but to memorize the short list of falsy values. There are only a handful of them.

Everything that is not on this list is truthy.

Here are the main falsy values in JavaScript:

  • false (the boolean)
  • 0 (the number zero)
  • "" (an empty string)
  • null
  • undefined
  • NaN (Not a Number)

This image provides a clear visual summary of these values.

JavaScript Falsy Values Explained
This image lists the core falsy values in JavaScript, such as `false`, `0`, `""`, `null`, `undefined`, and `NaN`. Each is shown in a code-like format with an explanatory comment.

Common "Truthy" Traps

Beginners often assume some values are falsy when they are, in fact, truthy. It's crucial to remember these:

  • "0" (a string containing the number zero)
  • "false" (a string containing the word "false")
  • " " (a string containing only a space)
  • [] (an empty array)
  • {} (an empty object)

The rule is simple: the only string that is falsy is an empty one (""). Any other string, no matter its content, is truthy. And surprisingly, empty arrays and objects are also truthy! We'll explore arrays and objects in great detail in future modules.

What are Falsy Values in JavaScript?

The freeCodeCamp article 'What are Falsy Values in JavaScript?' does an excellent job of breaking down each falsy value and highlighting these common truthy 'traps'.

First, read the section 'The Six Falsy Values in JavaScript' for clear examples of each falsy value. Then, jump to the section 'Truthy Values that May Appear as Falsy Values' to solidify your understanding of the common traps like empty arrays and the string '0'.

Test your understanding!

For each of the following values, decide if it's truthy or falsy.

  1. "hello"
  2. 0
  3. [] (an empty array)
  4. null
  5. " " (a string with a space)
  6. undefined
Show answer
  1. Truthy: It's a non-empty string.
  2. Falsy: The number zero is on our list of falsy values.
  3. Truthy: An empty array is one of the common "traps". It is truthy.
  4. Falsy: null is on our list of falsy values.
  5. Truthy: A string with a space is not an empty string, so it's truthy.
  6. Falsy: undefined is on our list of falsy values.

Use Case 1: Checking for the Presence of a Value

The most common use of truthy/falsy logic is to check if a variable has a "real" or meaningful value. For example, imagine you have a variable that should contain a user's name. You want to run some code only if the name has been provided.

The Old Way:

let userName = ""; // Let's say the user didn't enter anything

if (userName !== "" && userName !== null && userName !== undefined) {
  console.log(`Welcome, ${userName}!`);
} else {
  console.log("Welcome, guest!");
}

This is verbose and clunky.

The Truthy/Falsy Way:

let userName = "";

if (userName) { // Is userName truthy?
  console.log(`Welcome, ${userName}!`);
} else {
  console.log("Welcome, guest!");
}

This code does the exact same thing! If userName is an empty string "", null, or undefined, the condition is falsy, and the else block runs. If it contains a name like "Alice", it's truthy, and the first block runs.

JavaScript Truthy and Falsy Values - Explained in Detail

Let's return to the 'Future Fullstack' video. The next sections show this exact use case in action, first with a theoretical email signup form and then with a practical coupon code example in VS Code.

Watch from 02:58 to 06:55. Notice how the logic checks for the 'presence or absence' of a value without needing complex comparisons.


Use Case 2: Simplifying Boolean Checks

Another huge benefit is simplifying checks against boolean values. If you have a variable that you know is either true or false, you never need to compare it to true.

The Unnecessary Way:

let isLoggedIn = true;

if (isLoggedIn === true) {
  console.log("Access granted.");
}

The Simplified Way:

let isLoggedIn = true;

if (isLoggedIn) { // Is isLoggedIn truthy?
  console.log("Access granted.");
}

This works because isLoggedIn already holds a truthy value (true). If it were false, it would hold a falsy value, and the if block wouldn't run.

To check for a falsy value, you can use the logical NOT operator (!):

let hasPremiumAccess = false;

if (!hasPremiumAccess) { // Is hasPremiumAccess falsy?
  console.log("Please upgrade to access this feature.");
}

JavaScript Truthy and Falsy Values - Explained in Detail

The same video also covers this simplification technique beautifully. It shows several before-and-after examples that make the benefit crystal clear.

Watch from 06:55 to 13:59. This is a longer segment, but it's packed with practical examples like managing dark mode, login status, and website popups. Seeing the concept applied repeatedly will solidify your understanding.

Test your understanding!

The following function checks if a user is an admin and has more than 10 credits. Refactor it to be more concise using your knowledge of truthy values.

function canDeletePost(isAdmin, credits) {
  if (isAdmin === true && credits > 10) {
    return true;
  } else {
    return false;
  }
}
Show answer

Here is the refactored, more concise version:

function canDeletePost(isAdmin, credits) {
  return isAdmin && credits > 10;
}

Explanation:

  1. We remove === true because if isAdmin is true, it's already a truthy value.
  2. The && operator will result in a boolean (true or false) expression. We can directly return this result instead of using an if/else statement to return true or false manually.

A Deeper Dive: Default Values and the ?? Operator

A very common pattern that leverages falsy checks is setting a default value using the logical OR || operator.

const savedUsername = null;
const displayName = savedUsername || "Guest";

console.log(displayName); // Output: "Guest"

The || operator returns the first truthy value it finds. If savedUsername is null (falsy), the expression moves on and evaluates to "Guest".

However, this has a significant pitfall. What if 0 is a valid value?

let score = 0;
const finalScore = score || 10; // We want to keep 0, but it's falsy!

console.log(finalScore); // Output: 10 (This is a bug!)

Because 0 is falsy, the || operator skips it and assigns the default value 10.

To solve this, modern JavaScript (ES2020) introduced the nullish coalescing operator (??). This operator is similar to ||, but it only triggers on null or undefined. It treats 0 and "" as valid, truthy-like values.

let score = 0;
const finalScore = score ?? 10; // Only defaults if score is null or undefined

console.log(finalScore); // Output: 0 (Correct!)

This is a preview of the modern JavaScript syntax we'll cover later, but it's a perfect example of why a deep understanding of truthy/falsy values is crucial for writing robust code, especially when working with external data in frameworks like Next.js.

One Of the Most IMPORTANT Parts of JavaScript - Truthy and Falsy EXPLAINED

The video from dcode explains this || pattern and its pitfall, and then introduces the ?? operator as the modern solution.

Watch from 02:18 to the end of the video (05:20). Focus on how || is used for defaults, the problem it creates with the 'score' example, and how ?? solves that specific problem.


Conclusion

You've just unlocked a core concept of the JavaScript language. By understanding the distinction between truthy and falsy, you can make your code more readable, concise, and robust.

Key Takeaways:

  • In a boolean context (like an if statement), all values in JavaScript are treated as either "truthy" or "falsy".
  • The falsy values are false, 0, "", null, undefined, and NaN. Everything else is truthy.
  • Common "traps" for beginners are that empty arrays ([]), empty objects ({}), and non-empty strings like "0" are all truthy.
  • This knowledge allows you to write cleaner conditionals, such as if (variable) instead of if (variable !== null), and if (isLoggedIn) instead of if (isLoggedIn === true).
  • The || operator can set default values based on falsy checks, but be aware of its behavior with 0 and "". The modern ?? operator is often a safer choice.

Next Up:

We have now completed our module on controlling the flow of our programs with conditionals! You've learned how to make decisions using if/else, the ternary operator, switch, and now the powerful concepts of truthy and falsy values.

In our next lesson, we will begin a new module, Control Flow: Loops. We'll move from making one-time decisions to executing blocks of code repeatedly, starting with the fundamental for loop. This will enable us to perform repetitive tasks, which is essential for working with collections of data like arrays.