cf.completefrontendCode editorOpen lab
THE JAVASCRIPT FIELD GUIDE

Booleans & truthiness

Learn true and false, compare values, convert truthy and falsy inputs, avoid == true traps, and use booleans in practical JavaScript.

By the end, you can
  • 01
    Read boolean answersRecognize primitive true and false, and spot booleans produced by comparisons, methods, and !.
  • 02
    Predict truthinessUse the exact falsy list, then explain tricky truthy values like "false", [], and new Boolean(false).
  • 03
    Write safer conditionsConvert values deliberately, avoid == true, and choose practical patterns for toggles, arrays, forms, and URL strings.

true and false

A boolean is JavaScript's smallest yes/no answer. There are only two primitive boolean values: true and false. You will see them in variables with names like isOpen, hasItems, isLoggedIn, and checked.

The two boolean valuesPop out in the code editor (opens in a new tab)JavaScript
const isOpen = true;const hasItems = false;console.log(typeof true);console.log(isOpen);console.log(hasItems);

Line 3 prints "boolean" because true is a primitive boolean, not a string. Lines 4 and 5 print the values stored in yes/no variables. The variable names are not required, but names that start with is, has, or can make boolean code easy to read.

Definition

A boolean is exactly true or false. A value is truthy when JavaScript treats it like true in a condition, and falsy when JavaScript treats it like false.

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 exact falsy values
In real life: Everyone else comes in
In JavaScript: Every other ordinary 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.

This lesson stays focused on booleans. The engine-side story is in Booleans inside the engine. The later Booleans, null & undefined lesson compares booleans with the two common missing-value markers side by side.

Where booleans come from

STEP THROUGH

Beginners often write true and false directly first. Soon after, booleans start coming from questions: comparisons, methods that ask yes/no questions, and the not operator !.

Step through where booleans come from
Step 0 of 14Ready
Your turn: follow the blue line

Step through the ordinary places beginners first meet booleans: literal values, comparisons, method questions, and !.

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 hasItems = false;const trueType = typeof true;const bigger = 5 > 3;const sameLetter = "a" === "A";const hasEll = "hello".includes("ell");const isArray = Array.isArray([]);const isReallyNaN = Number.isNaN(NaN);const startsWithC = "cat".startsWith("c");const isClosed = !isOpen;console.log(isOpen, hasItems, trueType);console.log(bigger, sameLetter);console.log(hasEll, isArray, isReallyNaN, startsWithC);console.log(isClosed);
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.

Read the names out loud. bigger asks whether 5 > 3. hasEll asks whether the string contains a piece of text. isArray asks whether a value is an array. isClosed flips isOpen with !.

Boolean conversion: Boolean(), !!, if, and !

STEP THROUGH

Sometimes you already have a value and you want to know how JavaScript will treat it in a condition. Use Boolean(value) for the explicit answer. You will also see !!value, which uses two not operators to end up with the same primitive boolean.

Step through Boolean conversion
Step 0 of 7Ready
Your turn: follow the blue line

Compare Boolean(value), !!value, !value, and the branch chosen by if (value).

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 explicit = Boolean(value);const compact = !!value;const flipped = !value;if (value) {  console.log("truthy branch");} else {  console.log("falsy branch");}console.log(explicit, compact, flipped);
CallStoreChangeResultRun = next line. Ran = already executed.
Recent returnsNothing yet. Start with the blue line.
Value to convert

Changing the value starts a fresh replay. Watch line 4: one ! flips the answer.

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.

if (value) uses the same conversion to choose a branch. It does not change the original value. One ! flips the answer; two !! flips it back to the truthiness answer.

The eight falsy values

The everyday falsy list is short and exact. Memorize these eight values; every other ordinary JavaScript value is truthy.

  • false
  • 0
  • -0
  • 0n
  • ""
  • null
  • undefined
  • NaN
Browser curiosity: document.all

Browsers also give the old legacy object document.all special falsy behavior through ECMAScript Annex B's [[IsHTMLDDA]]. Treat that as compatibility trivia, not a normal value to use. The engine-side details fit better in Null inside the engine.

The surprises are all on the truthy side: "0", "false", " ", [], , functions, symbols, and wrapper objects all pass a truthiness check.

Truthiness playground

48 VALUES

Try many values and expressions. The playground shows Boolean(value), !!value, and the branch chosen by if (value). The computed-expression group includes classic bugs such as "abc".indexOf("a") returning 0 and floating-point math leaving a tiny truthy number.

Truthiness playground
Generated truthiness checkPop out in the code editor (opens in a new tab)JavaScript
const value = "0";console.log(Boolean(value));console.log(!!value);if (value) {  console.log("truthy branch");} else {  console.log("falsy branch");}
Real resultstruthy
Expression"0"
Value display"0"
Boolean(value)true
!!valuetrue
if branchtruthy branch

A non-empty string is truthy, even when it contains the character zero.

Try it yourself

"0" is truthy. Boolean(value) is true, !!value is true, and if (value) chooses the truthy branch. A non-empty string is truthy, even when it contains the character zero.

Every row is computed from a real JavaScript value. The source changes to the selected expression, then the results come from Boolean conversion.
Truthy or falsy sorter
  • false
  • 0
  • -0
  • 0n
  • ""
  • null
  • undefined
  • NaN
  • "0"
  • "false"
  • " "
  • []
  • {}
  • [""]
  • [[]]
  • function () {}
  • Symbol()
  • 1n
  • -1
  • Infinity
  • new Boolean(false)
  • new Number(0)
  • new String("")
  • /(?:)/
Try it yourself
0 of 24 correct

Sort each card using JavaScript’s exact truthiness rules. Watch for empty-looking objects and wrapper objects.

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

Here is every value from the playground at once, grouped the same way: empty values, strings, numbers, BigInts, objects, wrapper objects, and computed expressions. The middle column is computed from the real value when the page is built, not typed by hand.

All 48 playground values at a glance
ValueReads asWhy
truetruthytrue is already a boolean, so conversion leaves it as true.
falsefalsyThe boolean false is falsy by definition.
nullfalsynull means intentionally empty, and it is on the falsy list.
undefinedfalsyundefined means no value was supplied, and it is on the falsy list.
void 0falsyvoid always produces undefined, so this is falsy too.
""falsyOnly the string with zero characters is falsy.
"0"truthyA non-empty string is truthy, even when it contains the character zero.
"false"truthyJavaScript does not read the English word inside the string.
" "truthyA space is a character, so the string is not empty.
"\n"truthyA newline character still counts as one character.
"null"truthyThis is text, not the null value.
"undefined"truthyText that spells undefined is still a non-empty string.
"NaN"truthyThis is a string, not the special numeric NaN value.
0falsyNumber zero is falsy.
-0falsyNegative zero is still zero for truthiness.
NaNfalsyNaN is the one falsy not-a-number value.
-1truthyAny non-zero number is truthy, even a negative one.
0.1truthyAny non-zero decimal number is truthy.
InfinitytruthyInfinity is a number value and it is truthy.
-InfinitytruthyNegative infinity is also a non-zero number value, so it is truthy.
0nfalsyBigInt zero is falsy.
1ntruthyNon-zero BigInts are truthy.
-1ntruthyNegative BigInts are truthy unless they are exactly 0n.
[]truthyArrays are objects, and every ordinary object is truthy.
({})truthyObjects are truthy even when they have no properties.
[0]truthyThe array object is truthy even though its first item is falsy.
[""]truthyThe array is an object, so the falsy item inside does not make the array falsy.
[[]]truthyA nested array is still an object held inside another truthy array.
function () {}truthyFunctions are objects, and objects are truthy.
() => {}truthyArrow functions are function objects, so they are truthy.
Symbol()truthyEvery Symbol value is truthy.
new Date(0)truthyDate objects are objects, so they are truthy.
/(?:)/truthyRegular expression objects are truthy.
new Boolean(false)truthyThe wrapper object is truthy even though the primitive inside is false.
new Number(0)truthyA Number wrapper is an object, so it is truthy.
new String("")truthyA String wrapper is an object, so it is truthy even when it wraps empty text.
"abc".indexOf("a")falsyA found index can be 0, which is falsy. This is a classic indexOf bug.
"".lengthfalsyThe empty string has length zero, and zero is falsy.
Number("")falsyConverting an empty string to a number gives 0, which is falsy.
Number("abc")falsyA failed numeric conversion produces NaN, which is falsy.
parseInt("px")falsyNo leading digits means parseInt returns NaN, a falsy value.
1e-400falsyThis tiny number underflows to 0, so it is falsy.
0 * -1falsyThe calculation creates -0, and -0 is falsy.
[].lengthfalsyAn empty array is truthy, but its length is the falsy number 0.
" ".trim()falsyTrimming two spaces produces the empty string, which is falsy.
[1, 2].find((n) => n > 5)falsyWhen find finds nothing, it returns undefined, which is falsy.
5 - 5falsyThe result is numeric zero, so it is falsy.
0.1 + 0.2 - 0.3truthyFloating-point rounding leaves a tiny non-zero number, so it is truthy.

Booleans in conditions and logic

Conditions use truthiness. The ! operator returns a primitive boolean. The logical operators && and || are a little different: they choose and return one of their original operands. The full lesson is Logical operators; here is the beginner preview.

Logical operators return operandsPop out in the code editor (opens in a new tab)JavaScript
const name = "";const fallback = name || "friend";const subscribed = true;const access = subscribed && "member area";console.log(fallback);console.log(access);console.log(!subscribed);

Line 2 returns the fallback string because name is the empty string. Line 4 returns the string "member area", not the boolean true. Line 7 uses !, so it prints a real boolean.

Boolean objects and equality traps

TRAPS

Boolean(x) without new returns a primitive boolean. new Boolean(false) creates an object wrapper. Objects are truthy, so the wrapper is dangerous in conditions.

Boolean object versus primitivePop out in the code editor (opens in a new tab)JavaScript
const boxed = new Boolean(false);console.log(Boolean(boxed));console.log(typeof boxed);console.log(boxed.valueOf());console.log(Boolean(false));
Never use new Boolean for app state

If you need a boolean, write true, false, Boolean(value), or a comparison. Avoid new Boolean(...), new Number(...), and new String(...) for beginner application code.

A second trap is comparing values with == true or == false. When loose equality sees a boolean, it converts toward numbers. That creates surprising results.

The == true trapPop out in the code editor (opens in a new tab)JavaScript
console.log("1" == true);console.log("true" == true);console.log([] == false);console.log(Boolean([]));
Truthiness is not the same as == true
ValueBoolean(value)value == truevalue == false
"1"truetruefalse
"true"truefalsefalse
[]truefalsetrue
0falsefalsetrue
"false"truefalsefalse

Prefer if (value) when you mean “truthy,” or value === true when you require the primitive boolean true exactly.

Practical booleans

Booleans show up in interface state, form controls, array checks, filters, and URL parsing. The pattern depends on what question you are asking.

  • Toggles: flip a boolean with isOpen = !isOpen.
  • Form controls: a checkbox exposes a boolean .checked property.
  • Arrays: use if (items.length) to ask whether the list has items.
  • Cleanup: array.filter(Boolean) removes falsy values, including 0.
  • Strings from URLs or forms: parse "true" and "false" with exact comparisons.
Toggle and checkbox booleansPop out in the code editor (opens in a new tab)JavaScript
let isOpen = false;isOpen = !isOpen;console.log(isOpen);const checkbox = { checked: true };console.log(checkbox.checked);
Item count and filter(Boolean)Pop out in the code editor (opens in a new tab)JavaScript
const items = ["hat", "coat"];if (items.length) {  console.log("show cart");}const mixed = [0, 1, "", "Ada", null, false, true];console.log(mixed.filter(Boolean).join("|"));
Parse true/false strings deliberatelyPop out in the code editor (opens in a new tab)JavaScript
const fromUrl = "false";console.log(Boolean(fromUrl));console.log(fromUrl === "true");console.log(fromUrl === "false" ? false : fromUrl === "true");

Common misconceptions

  • “The string "false" is false.” It is a non-empty string, so it is truthy.
  • “Whitespace is empty.” " " and "\n" contain characters and are truthy.
  • “Empty arrays and objects are falsy.” They are objects, and ordinary objects are truthy.
  • “new Boolean(false) behaves like false.” It is an object, so it is truthy.
  • “== true checks truthiness.” It follows loose-equality conversions instead.
  • “filter(Boolean) only removes missing values.” It removes every falsy value, including 0.
  • “if (value) is a missing-value check.” It also rejects false, 0, "", and NaN.

Practice exercises

6 EXERCISES
Exercise 1 · Warm-upPredict booleans from questions

Predict the four outputs in order.

Starter codePop out in the code editor (opens in a new tab)JavaScript
console.log(typeof true);
console.log(5 > 3);
console.log("a" === "A");
console.log(!"hello".includes("z"));

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

    Exercise 2 · Warm-upCount the falsy values

    How many values are on the exact falsy list?

    Starter codePop out in the code editor (opens in a new tab)JavaScript
    const falsy = [false, 0, -0, 0n, "", null, undefined, NaN];
    console.log(falsy.length);
    console.log(falsy.every((value) => !value));

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

      Exercise 3 · PracticeParse a URL boolean

      The URL gave you the string "false". What should the exact comparison print?

      Starter codePop out in the code editor (opens in a new tab)JavaScript
      const raw = "false";
      console.log(Boolean(raw));
      console.log(raw === "true");

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

        Exercise 4 · PracticeKnow what filter(Boolean) keeps

        What does the filtered list print?

        Starter codePop out in the code editor (opens in a new tab)JavaScript
        const values = [0, 1, 2, "", "ok", null, false, true];
        console.log(values.filter(Boolean).join("|"));

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

          Exercise 5 · PracticeFind the indexOf bug

          The code prints missed even though "a" is in the string. Why?

          Starter codePop out in the code editor (opens in a new tab)JavaScript
          const position = "abc".indexOf("a");
          if (position) {
            console.log("found");
          } else {
            console.log("missed");
          }

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

            Exercise 6 · ChallengeAvoid Boolean wrapper objects

            Predict the three outputs.

            Starter codePop out in the code editor (opens in a new tab)JavaScript
            const boxed = new Boolean(false);
            console.log(Boolean(boxed));
            console.log(typeof boxed);
            console.log(Boolean(false));

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

              Check your understanding

              8 QUESTIONS
              Booleans & truthiness quiz · 8 questionsScore: first tries count
              1. Question 1 of 8How many primitive boolean values does JavaScript have?

                Choose an answer to see the explanation.

              2. Question 2 of 8What do the comparison and method print?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                console.log(5 > 3);
                console.log("hello".includes("z"));

                Choose an answer to see the explanation.

              3. Question 3 of 8What does this 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.

              4. Question 4 of 8What do the empty and space strings print?

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

                Choose an answer to see the explanation.

              5. Question 5 of 8What does this array check print?

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

                Choose an answer to see the explanation.

              6. Question 6 of 8What do these loose equality checks print?

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

                Choose an answer to see the explanation.

              7. Question 7 of 8What does a Boolean object do?

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

                Choose an answer to see the explanation.

              8. Question 8 of 8What does this tiny number print?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                console.log(Boolean(0.1 + 0.2 - 0.3));

                Choose an answer to see the explanation.

              Key takeaways

              • Primitive booleans are exactly true and false.
              • Comparisons, yes/no methods, and ! produce primitive booleans.
              • The everyday falsy list is false, 0, -0, 0n, "", null, undefined, and NaN.
              • Everything else ordinary is truthy, including "false", [], , and new Boolean(false).
              • Avoid == true; use if (value) for truthiness or value === true for the exact primitive.
              • Use practical checks carefully: items.length, filter(Boolean), and raw === "true" each answer different questions.

              Final definition: a boolean is the primitive yes/no value true or false; truthiness is JavaScript's automatic boolean reading of any value.

              Up next: undefined, the value JavaScript uses when something has not been supplied yet.

              CompleteFrontend Clear concepts. Working examples.