Truthy Objects That Seem Falsy
You'll learn why wrapped Boolean objects can trick you, even when they wrap false.
When you create a Boolean using new Boolean(false), you might expect it to act like false in conditions. Surprise: it doesn't! It's actually truthy.
The Wrapper Object Trap
Remember from earlier lessons that everything in JavaScript is either truthy or falsy. Objects are always truthy, even if they're wrapping a falsy value:
const wrappedFalse = new Boolean(false);
if (wrappedFalse) {
console.log("This runs!"); // Executes!
}
Why? Because wrappedFalse isn't the primitive false—it's an object. JavaScript sees the object container, not what's inside. All objects coerce to true in boolean contexts.
The Primitive Inside Doesn't Matter
The same trap exists for other wrapper objects:
const wrappedZero = new Number(0);
const wrappedEmptyString = new String("");
if (wrappedZero) {
console.log("Zero object is truthy!"); // Runs
}
if (wrappedEmptyString) {
console.log("Empty string object is truthy!"); // Runs
}
Even though 0 and "" are falsy primitives, their wrapper objects are truthy because the object itself is what gets evaluated, not its wrapped value.
Think of It Like Gift Wrapping
Imagine wrapping nothing in a box. The box still exists—you can see it and hold it. JavaScript treats the box (object) as "something," even if the contents (primitive value) would normally be "nothing."
This is why you should generally avoid using new Boolean(), new Number(), or new String(). Stick with primitive values unless you have a specific reason to create wrapper objects.
Key Takeaway: Wrapper objects created with new Boolean(false), new Number(0), etc. are always truthy because JavaScript evaluates the object container, not the primitive value inside.