iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

JS Booleans

A boolean is true or false. JavaScript also converts other values to booleans in any boolean context — that's called truthiness.

Falsy values (the whole list)

  • false
  • 0 and -0
  • 0n (BigInt zero)
  • "" (empty string)
  • null
  • undefined
  • NaN

Everything else is truthy — including "false", "0", [], {}.

Coerce explicitly

JS
Boolean("")       // false
Boolean("hi")     // true
Boolean(0)        // false
Boolean(null)     // false

!!"hi"            // true   — common shortcut for Boolean(x)
!!0               // false

Boolean methods you'll use

Property / methodWhat it does
arr.some(fn)True if any item passes a test.
arr.every(fn)True if all items pass.
arr.includes(x)True if x is in the array.
"…".startsWith(p)String prefix test.
Number.isFinite(x)True for real numbers — false for NaN/Infinity.
Number.isNaN(x)True only for NaN (safer than global isNaN).
Tip: Filter falsies out of an array in one line: arr.filter(Boolean). Hands the items to Boolean() as the predicate.

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from JS Booleans!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Coerce any value to a boolean in one expression.

const bool = x;

Test yourself

Q1. Which is NOT falsy?
Q2. Quickly convert to boolean with…
Q3. `arr.filter(Boolean)` removes…

Discussion

Loading…