cf.completefrontendCode editorOpen lab
THE JAVASCRIPT FIELD GUIDE

Booleans, null & undefined

Learn true, false, JavaScript’s eight falsy values, and the difference between intentional null and not-yet-filled undefined.

By the end, you can
  • 01
    Predict truthinessName the eight falsy values and explain why tricky values like [] are truthy.
  • 02
    Separate null from undefinedUse each missing-value marker for the job it actually means.
  • 03
    Check missing values safelyAvoid bugs where 0 or "" is rejected as missing.

The yes/no family

JavaScript often needs a plain yes or no. Is the menu open? Did the user finish the form? Should this message be visible? The two boolean values answer those questions: true means yes, and false means no.

Two booleansPop out in the code editor (opens in a new tab)JavaScript
const subscribed = true;const muted = false;console.log(subscribed);console.log(muted);

This lesson puts two neighbors beside them: null and undefined. They are not booleans, but they often stand near boolean decisions because JavaScript must also ask, “Do I have a value at all?” Each value has its own lesson (Booleans & truthiness, undefined, and null); here you compare them side by side and choose the right check.

Definition

A boolean is either true or false. A truthy value behaves like true in a condition; a falsy value behaves like false. null means intentionally nothing, while undefined means no value has been supplied yet.

Real-life analogyTruthiness is a guest list with a few names

Imagine a guest list with only a few names on the no list. Those names are no; everyone else is yes. Truthiness works the same way with its eight falsy values.

In real life: Names on the short no list
In JavaScript: The eight falsy values
In real life: Everyone else comes in
In JavaScript: Every other value is truthy
In real life: The word false on a name tag
In JavaScript: The string "false" is truthy

Where the analogy stops: A real guest list can change. JavaScript uses the same built-in falsy list every time.

We will use tiny if statements in this lesson because they are the easiest way to see truthiness. Control flow gets a full lesson later; for now, read if (value) as “if this value gets treated like true.”

Truthy & falsy

INTERACTIVE

JavaScript does not require a condition to be literally true or false. Before an if chooses a branch, JavaScript converts the value to a boolean. The complete falsy list is short enough to memorize:

  • false
  • 0 and -0
  • 0n, BigInt zero
  • "", the empty string
  • null
  • undefined
  • NaN

Everything else is truthy. That includes "0", "false", " ", [], , -1, and Infinity. This is why truthiness is useful for “is there something here?” but dangerous when zero or an empty string is a valid answer.

Truthy or falsy?
  • false
  • 0
  • -0
  • 0n
  • ""
  • null
  • undefined
  • NaN
  • "0"
  • "false"
  • " "
  • []
  • {}
  • -1
  • Infinity
Try it yourself
0 of 15 correct

Sort each value using JavaScript’s exact truthiness rules.

Choose a category for every card. You can change an answer at any time; Reset clears them all.

Test truthiness for real

PLAYGROUND

Pick a value and watch three common checks agree: Boolean(value), !!value, and the branch chosen by if (value). The double exclamation mark is a common shorthand for “turn this into a real boolean.”

Truthiness tester
const value = false;console.log(Boolean(value));console.log(!!value);if (value) {  console.log("truthy branch");} else {  console.log("falsy branch");}
Real resultsfalsy
Boolean(value)false
!!valuefalse
if branchfalsy branch
Whyfalse is the boolean value that means no.
Try it yourself

false is falsy. Boolean(value) is false, !!value is false, and the if statement runs the falsy branch. false is the boolean value that means no.

The code is regenerated for the selected value. The results come from JavaScript’s actual Boolean conversion.

Notice the pattern: values that are empty containers are not necessarily falsy. An empty array is still an array object. An empty object is still an object. To ask whether a list has items, check its length; do not trust the array object itself.

null vs undefined

COMPARE

null and undefined both mean “no useful value here,” but they tell different stories. null is a form field you cleared on purpose. undefined is a field nobody has filled in yet.

Real-life analogyA form field: cleared or unfilled

If you clear a profile photo, storing null says “there is intentionally no photo now.” If code asks for a property that was never put on an object, JavaScript gives undefined because nobody filled that field.

In real life: You clear the field
In JavaScript: You assign null on purpose
In real life: Nobody fills in the field
In JavaScript: A missing property or argument is undefined
In real life: The cleared field stays empty
In JavaScript: null communicates a choice

Where the analogy stops: JavaScript will not enforce your intention. Your team’s code style decides when to assign null.

How null and undefined differ
Questionnullundefined
Main meaningIntentionally emptyNot supplied or not created
Who usually sets it?Your code or an API that deliberately says nothing was foundJavaScript when a value is missing
typeof"object" (a famous historical quirk)"undefined"
Loose comparisonnull == undefined is trueundefined == null is true
Strict comparisonnull === undefined is falseundefined === null is false
JSON.stringify in objectsKept as nullProperty is omitted

You saw typeof null in the Data types lesson: it returns "object". Treat that as an old quirk, not as a sign that null works like a normal object.

Where missing values appear

STEP THROUGH

undefined appears in several ordinary places: an uninitialized let, a missing object property, a function with no return, a missing argument, or an array index that is out of range. null appears when code sets it deliberately, and some browser APIs return it when they find nothing. For example, document.querySelector(".missing") returns null in most browsers when no element matches. In the Talking to the user lesson, prompt can also return null when the user cancels.

Where undefined appears
Step 0 of 10Ready
Your turn: follow the blue line

Step through common places undefined appears, then compare them with one deliberate null.

Running in
  1. script
Next: line 1
Click the blue line to take the next stepPop out in the code editor (opens in a new tab)JavaScript
const profile = { name: "Ada" };function noReturn() {  const message = "done";}function echo(nickname) {  return nickname;}const list = ["first"];const deliberatelyEmpty = null; console.log(notFilled);console.log(profile.age);console.log(noReturn());console.log(echo());console.log(list[3]);console.log(deliberatelyEmpty);
CallStoreChangeResultRun = next line. Ran = already executed.
Recent returnsNothing yet. Start with the blue line.
A guided replay recorded from real JavaScript calls, not an engine debugger. Step follows executed statements; Back reviews a snapshot. Reset starts a fresh run.

Checking for missing values

STEP THROUGH

The hardest beginner bug is confusing “missing” with “falsy.” If a quantity can be 0, or a name can be an empty string, if (value) is too broad. Compare four checks side by side.

Compare four missing-value checks
Step 0 of 5Ready
Your turn: follow the blue line

Change the value, then compare truthiness, exact undefined, loose null, and nullish fallback.

Running in
  1. script
Next: line 1
Click the blue line to take the next stepPop out in the code editor (opens in a new tab)JavaScript
console.log(Boolean(name));console.log(name === undefined);console.log(name == null);console.log(name ?? "friend");
CallStoreChangeResultRun = next line. Ran = already executed.
Recent returnsNothing yet. Start with the blue line.
Value passed to the checks

Changing the value starts a fresh replay. Watch especially how 0 and "" behave.

A guided replay recorded from real JavaScript calls, not an engine debugger. Step follows executed statements; Back reviews a snapshot. Reset starts a fresh run.

Two patterns are especially useful. Use value == null when you intentionally want to catch both null and undefined and nothing else. Use value ?? fallback, the nullish coalescing operator, when only null or undefined should fall back. The Operators module will spend a full lesson on comparisons, logical operators, nullish coalescing, and optional chaining.

Where you’ll use this

Boolean and missing-value checks appear in real interfaces constantly: optional form fields, shopping-cart quantities, feature toggles, search filters, and API responses. The key question is always: “Am I testing yes/no, or am I testing whether a value is missing?”

Keep zero as a real quantityPop out in the code editor (opens in a new tab)JavaScript
function labelQuantity(quantity) {  if (quantity == null) {    return "missing";  }  return quantity + " selected";}console.log(labelQuantity(0));

This code accepts 0 as a real quantity. It only reports missing when the caller passes null or undefined.

Common misconceptions

  • “Empty arrays are falsy.” They are truthy. Check array.length instead.
  • “The string "false" is false.” It is a non-empty string, so it is truthy.
  • “null and undefined are identical.” They are loosely equal but strictly different.
  • “typeof null proves null is an object.” It is a historical result; do not use properties on null.
  • “if (value) is a safe missing-value check.” It also rejects 0, "", false, and NaN.
The empty-array trapPop out in the code editor (opens in a new tab)JavaScript
const cartItems = []; if (cartItems) {  console.log("cart exists");} if (cartItems.length === 0) {  console.log("cart is empty");}

Practice exercises

5 EXERCISES
Exercise 1 · Warm-upPredict three truthiness checks

Predict each line in order. Separate the outputs with commas.

Starter codePop out in the code editor (opens in a new tab)JavaScript
console.log(Boolean("0"));
console.log(Boolean(""));
console.log(Boolean([]));

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · PracticeFix the zero quantity bug

    The function says 0 is missing. Change the check so zero is accepted.

    Starter codePop out in the code editor (opens in a new tab)JavaScript
    function labelQuantity(quantity) {
      if (!quantity) {
        return "missing";
      }
      return quantity + " selected";
    }
    console.log(labelQuantity(0));

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeChoose null or undefined

      A user clicks “Clear photo.” Should the app store null or leave the field undefined?

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeWrite a nullish fallback

        Which operator makes displayName(null) return "friend" but keeps ""?

        Starter codePop out in the code editor (opens in a new tab)JavaScript
        function displayName(name) {
          return name ?? "friend";
        }
        console.log(displayName(null));
        console.log(displayName(""));

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeExplain the empty-array trap

          What property should code check when it needs to know whether a list is empty?

          Starter codePop out in the code editor (opens in a new tab)JavaScript
          const items = [];
          console.log(Boolean(items));
          console.log(items.length === 0);

          Answer, then press Check. Spacing and letter case don’t matter.

            Check your understanding

            7 QUESTIONS
            Booleans, null & undefined quiz · 7 questionsScore: first tries count
            1. Question 1 of 7How many falsy values are on JavaScript’s short list?

              Choose an answer to see the explanation.

            2. Question 2 of 7What does Boolean("false") print?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              console.log(Boolean("false"));

              Choose an answer to see the explanation.

            3. Question 3 of 7What does Boolean([]) print?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              console.log(Boolean([]));

              Choose an answer to see the explanation.

            4. Question 4 of 7Which statement best describes null?

              Choose an answer to see the explanation.

            5. Question 5 of 7What do the loose and strict null comparisons print?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              console.log(null == undefined);
              console.log(null === undefined);

              Choose an answer to see the explanation.

            6. Question 6 of 7What does nullish coalescing do with zero?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              const quantity = 0;
              console.log(quantity ?? 1);

              Choose an answer to see the explanation.

            7. Question 7 of 7Which check treats both null and undefined as missing, but not 0 or ""?

              Choose an answer to see the explanation.

            Key takeaways

            • Booleans are exactly true and false.
            • Falsy values are exactly false, 0, -0, 0n, "", null, undefined, and NaN.
            • Every object is truthy, including [] and .
            • Use null for intentional emptiness and expect undefined when a value was not supplied.
            • Use == null or ?? when you mean missing, not merely falsy.

            Final definition: Truthiness is JavaScript’s automatic yes/no reading of any value; null and undefined are the two common ways it says “no value.”

            Up next: BigInt.

            CompleteFrontend Clear concepts. Working examples.