Sub topic 4
Converting Explicitly with Boolean() and !!
This chapter assumes you know how to declare variables with let and const, write and call functions, and read console.log output. It also assumes you have read the earlier chapters on boolean contexts and the falsy list. Those chapters showed JavaScript converting values to booleans implicitly, inside if, while, and the ternary operator. This chapter covers doing the same conversion on purpose, so your code holds a real true or false value rather than a truthy or falsy one.
Why Convert Explicitly at All
Inside an if condition you rarely need to convert anything, because the engine does it for you. The difference matters once a value leaves the condition and travels somewhere else:
- A function documented as returning a boolean should return
trueorfalse, not"[email protected]"or0. - A value stored in state, sent as JSON, or written to a database column typed as boolean should be an actual boolean.
- A strict comparison like
isReady === truefails whenisReadyholds a truthy non-boolean such as1. - UI frameworks that render expression results, such as React, display a stray
0on the page but render nothing forfalse.
Explicit conversion turns a truthy or falsy value into the boolean the engine would have used internally. The two common ways to do it are the Boolean() function and the double negation !!.
The ToBoolean Rule Behind Both Forms
The language specification defines one internal operation, called ToBoolean, that every boolean context uses. Boolean(x) and !!x both apply this same operation, so they always give the same result. The rule is a lookup and needs no computation:
| Input type | Result |
|---|---|
| Undefined, Null | `false` |
| Boolean | the value itself |
| Number | `false` for `0`, `-0`, `NaN`; otherwise `true` |
| BigInt | `false` for `0n`; otherwise `true` |
| String | `false` for `""`; otherwise `true` |
| Symbol | always `true` |
| Object (including arrays, functions, wrappers) | always `true` |
The object row has an important consequence. ToBoolean never calls valueOf, toString, or Symbol.toPrimitive. An object cannot customize its truthiness, however it is written.
const sneaky = {
valueOf() { return 0; },
toString() { return ""; },
[Symbol.toPrimitive]() { return false; }
};
console.log(Boolean(sneaky)); // true
console.log(!!sneaky); // true
console.log(sneaky + 1); // 1 (numeric conversion DOES use the hook)The hooks take part in numeric and string conversion, but boolean conversion ignores them completely.
Using Boolean() as a Function
Call Boolean without new and it returns a primitive boolean:
console.log(Boolean("hello")); // true
console.log(Boolean(0)); // false
console.log(Boolean(0n)); // false
console.log(Boolean(NaN)); // false
console.log(Boolean(Symbol())); // true
console.log(Boolean([])); // true
console.log(Boolean()); // false (no argument means undefined)
console.log(typeof Boolean(1)); // "boolean"Boolean() with no argument returns false because the missing argument is undefined. This matters when Boolean is passed as a callback that might be called with no arguments.
Passing Boolean as a Callback
Boolean is an ordinary function, so you can pass it anywhere a predicate is expected. The best-known use is filter(Boolean):
const raw = ["apple", "", null, "pear", undefined, "plum"];
const names = raw.filter(Boolean);
console.log(names); // ["apple", "pear", "plum"]filter passes three arguments (element, index, array), but Boolean reads only the first one, so the extra arguments do no harm. That makes it safer than map(parseInt), which is known to misbehave because parseInt uses its second argument as the radix.
const scores = [10, 0, null, 7, undefined, 0];
console.log(scores.filter(Boolean)); // [10, 7] (zeros lost)
console.log(scores.filter(x => x != null)); // [10, 0, 7, 0]The new Boolean() Trap
Calling Boolean with new does something different. It creates a wrapper object around the boolean, and every object is truthy:
const wrapped = new Boolean(false);
console.log(typeof wrapped); // "object"
console.log(Boolean(wrapped)); // true
console.log(wrapped === false); // false
console.log(wrapped.valueOf()); // false
if (wrapped) {
console.log("this runs, even though it wraps false");
}The same applies to new Number(0) and new String(""). Both are truthy objects. There is almost never a reason to construct these wrappers. Linters such as ESLint flag them with the no-new-wrappers rule.
How !! Works Step by Step
The logical NOT operator ! applies ToBoolean to its operand and then flips the result. So !x always returns a real boolean, just the inverted one. Applying ! a second time flips it back, which leaves you with ToBoolean of the original value.
const input = "hi";
console.log(!input); // false (truthy, inverted)
console.log(!!input); // true (inverted back)
console.log(!!null); // false
console.log(!!"0"); // true
console.log(!!{}); // true
console.log(!!-0); // false
console.log(!!new Boolean(false)); // true (still an object)!! is not a separate operator. It is two ! operators next to each other, and a third ! would invert the result again. !!!x gives the same result as !x, and writing it only confuses readers.
Boolean() Versus !!
Both forms produce the same result for every input, so the choice comes down to readability and context.
| Aspect | `Boolean(x)` | `!!x` |
|---|---|---|
| Result | primitive boolean | primitive boolean |
| Readability for newcomers | self-describing | needs to be learned |
| Usable as a callback | yes, `arr.filter(Boolean)` | no, needs `x => !!x` |
| Can be shadowed | yes, if a local variable named `Boolean` exists | no |
| Speed | no measurable difference in modern engines | no measurable difference |
Many teams use Boolean(x) in application code because it reads clearly, and accept !!x in short expressions. Pick one style and apply it across the codebase. A linter rule such as ESLint's no-implicit-coercion can enforce the choice.
Practical Patterns
Returning a Boolean from a Predicate
A function named like a question (hasX, isY) should return a boolean. An && chain returns one of its operands (covered in the && chapter), so wrap it:
function hasEmail(user) {
return Boolean(user && user.email);
}
console.log(hasEmail({ email: "[email protected]" })); // true
console.log(hasEmail({ email: "" })); // false
console.log(hasEmail(null)); // falseIf you leave out Boolean, the function returns "[email protected]", "", or null. These behave correctly inside an if, but they break a strict check like hasEmail(u) === true.
Serializing Flags
const form = { newsletter: "on", terms: undefined };
const payload = {
newsletter: Boolean(form.newsletter),
terms: Boolean(form.terms)
};
console.log(JSON.stringify(payload)); // {"newsletter":true,"terms":false}
console.log(JSON.stringify(form)); // {"newsletter":"on"} (terms vanished)JSON.stringify drops properties whose value is undefined. Converting first keeps the key present and typed.
Counting Truthy Values
Booleans convert to 1 and 0 in arithmetic, so a converted value can be summed:
const checks = ["x", "", 0, "y", null];
const passed = checks.reduce((n, v) => n + Number(Boolean(v)), 0);
console.log(passed); // 2Edge Cases That Conversion Will Not Fix
Explicit conversion applies truthiness. It does not parse meaning. The string "false" is non-empty, so it converts to true. The same goes for "0" and "no":
console.log(Boolean("false")); // true
console.log(Boolean("0")); // true
function parseFlag(text) {
const normalized = String(text).trim().toLowerCase();
if (normalized === "true" || normalized === "1") return true;
if (normalized === "false" || normalized === "0" || normalized === "") return false;
throw new Error(`Not a boolean flag: ${text}`);
}
console.log(parseFlag("false")); // false
console.log(parseFlag(" TRUE ")); // trueQuery strings, environment variables, and form fields always arrive as strings. Converting them with Boolean() treats every non-empty value as true, which is rarely what you want. Compare against the exact strings you expect instead.
Watch for one more edge case. Converting with Boolean() throws away information. Boolean(0) and Boolean(null) both return false, so you can no longer tell "zero items" apart from "no data". Convert at the point where you need a boolean, not earlier.
Exercise
What does each line print? console.log(Boolean(new Number(0))); console.log(!!" "); console.log(!!!""); console.log(Boolean());
Show answer
true, true, true, false. new Number(0) is a wrapper object, and every object is truthy. " " is a non-empty string because spaces count as characters. !!!"" is !(!!""), which is !false, so true. Boolean() with no argument converts undefined, so false.
Exercise
A function isAdmin(user) is written as return user && user.role === "admin"; Calling isAdmin(null) === false returns false. Why, and how do you fix it?
Show answer
When user is null, the && expression returns its first falsy operand, null, so the function returns null. null === false is false. Fix it with return Boolean(user && user.role === "admin"); or with optional chaining, return user?.role === "admin"; which always produces a boolean from the strict comparison.
Exercise
You run [3, 0, null, 5, NaN, undefined].filter(Boolean) and expected [3, 0, 5]. What do you get, and what filter produces [3, 0, 5]?
Show answer
You get [3, 5], because Boolean drops 0 and NaN along with null and undefined. To keep 0 but drop NaN and the nullish values, use .filter(x => x != null && !Number.isNaN(x)), which returns [3, 0, 5].