14

In the Google JavaScript style guide, it says not to use wrapper objects for primitive types. It says it's "dangerous" to do so. To prove its point, it uses the example:

var x = new Boolean(false);
if (x) {
  alert('hi');  // Shows 'hi'.
}

OK, I give up. Why is the if code being executed here?

Bill
  • 561
  • 6
  • 15

4 Answers4

20

Because every variable that is typeof Object is truthy and wrappers are objects.

marc
  • 6,103
  • 1
  • 28
  • 33
  • So basically you're saying that x is _not_ being assigned the value false as I thought it was. It's being assigned an "object", which evaluates to true. – Bill Jul 29 '11 at 18:16
  • Yes, an object that wraps the value, but as it is an object, it is truthy. – marc Jul 30 '11 at 16:21
  • 1
    `typeof null` -> "object", `!!null` -> false. Correct me if I'm wrong, but I believe nulls are falsy objects and a rather important exception to the above stated absolute rule. – Patrick Apr 03 '13 at 20:40
  • @Patrick `null` isn't an object. See [this](http://stackoverflow.com/a/18808270/894284). – Matt Fenwick Mar 05 '14 at 23:15
  • @MattFenwick I should have just said "nulls are falsy" and excluded the word "objects". Otherwise, I believe my comment still makes sense in context. Just because you have an `x` such that `typeof x` yields `"object"` is not a valid way to check that `x` is truthy. – Patrick Mar 07 '14 at 18:24
12

if(x) will run if x is truthy.

x is truthy if it's not falsey.

x is falsey if x is null, undefined, 0, "", false

So since new Boolean(false) is an Object and an Object is truthy, the block runs

Matthias
  • 13,607
  • 9
  • 44
  • 60
Raynos
  • 166,823
  • 56
  • 351
  • 396
2

In the if(x) case, it's actually evaluating the default Boolean of the object named and not its value of false.

So be careful using Boolean objects instead of Boolean values. =)

Collin Graves
  • 2,207
  • 15
  • 11
0

The following code uses a Boolean object. The Boolean object is false, yet console.log("Found") still executes because an object is always considered true inside a conditional statement. It doesn’t matter that the object represents false; it’s an object, so it evaluates to true.

var found = new Boolean(false);
if (found) 
{    console.log("Found");
       // this executes
}
Machavity
  • 30,841
  • 27
  • 92
  • 100