Sub topic 4
Converting Explicitly with Boolean() and !!
This chapter assumes you know the falsy values from the previous chapter. It also assumes you can write functions and read console.log output. So far, JavaScript has done the conversion to a boolean for you, inside if, while or a ternary. Sometimes you need the boolean itself as a value. You might want to store it, return it from a function, or send it as JSON. For that, JavaScript gives you two explicit tools.
Boolean() as a Function
Boolean(value) applies the same truthiness rules that an if statement uses and returns a real true or false. It never returns anything else.
console.log(Boolean("hello")); // true
console.log(Boolean(0)); // false
console.log(Boolean("")); // false
console.log(Boolean([])); // true
console.log(typeof Boolean(1)); // "boolean"Call it without new. Boolean(x) gives you a primitive boolean, and that is almost always what you want.
The ! and !! Operators
The ! operator converts its operand to a boolean and then negates it. A second ! negates the result again. That leaves the boolean that matches the original value's truthiness.
console.log(!!"hello"); // true
console.log(!!0); // false
console.log(!""); // trueFor every input, !!x and Boolean(x) return the same result. Which one you use is a style choice:
| Form | Strength | Weakness |
|---|---|---|
| `Boolean(x)` | Reads clearly to newcomers | Slightly longer |
| `!!x` | Short and widely used | Easy to misread as one `!` |
Pick one form for your codebase and use it everywhere.
Where Explicit Conversion Helps
Returning a clean boolean
A predicate function should return true or false. It should not return whatever value happened to decide the result.
function hasName(user) {
return !!user.name;
}
console.log(hasName({ name: "Ada" })); // true
console.log(hasName({ name: "" })); // false
console.log(hasName({})); // falseIf the function returned user.name without converting it, callers would get "Ada", "" or undefined. Logging or serializing those values gives confusing output.
Filtering out falsy entries
Boolean is an ordinary function, so you can pass it straight to array methods:
const raw = [0, "a", "", null, 42, NaN, undefined];
console.log(raw.filter(Boolean)); // ["a", 42]Be careful with this. The filter removes every falsy value, including a valid 0 or "", so use it only when you really want those values gone.
Storing flags
const input = " ";
const state = { hasInput: Boolean(input.trim()) };
console.log(JSON.stringify(state)); // {"hasInput":false}Common Errors
const wrapped = new Boolean(false);
console.log(typeof wrapped); // "object"
if (wrapped) console.log("this runs"); // logs "this runs"
console.log(Boolean(wrapped)); // trueTwo other mistakes come up often:
- Converting inside a condition for no reason.
if (!!items.length)behaves exactly likeif (items.length), because theifalready converts the value. The extra!!only adds noise. - Expecting conversion to parse strings.
Boolean("false")and!!"0"are bothtrue, because any non-empty string is truthy. To read text such as"false"as a boolean, compare it directly:text === "true".
Exercise
What does this code log? console.log([0, "", [], "0", new Boolean(false)].map(v => !!v));
Show answer
[false, false, true, true, true]. 0 and "" are falsy. An empty array is an object, so it is truthy. "0" is a non-empty string, so it is truthy. new Boolean(false) is a wrapper object, so it is truthy too.
Exercise
A function isLoggedIn(session) returns session && session.userId. A caller logs its result and sometimes sees undefined, null or a number such as 17. Rewrite the function so it always returns true or false.
Show answer
function isLoggedIn(session) { return Boolean(session && session.userId); } You can also write return !!(session && session.userId);. Both convert whichever operand && returns into a primitive boolean.