JavaScript style: don't use wrapper objects for primitive types
Asked Answered
D

4

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?

Dumbwaiter answered 29/7, 2011 at 18:4 Comment(2)
Because Boolean(false) === !(new Boolean(false)). And Boolean(false) === new Boolean(false).valueOf().Juanajuanita
@katspaugh: that makes it much clearer -- thanks.Dumbwaiter
M
20

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

Misjudge answered 29/7, 2011 at 18:6 Comment(5)
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.Dumbwaiter
Yes, an object that wraps the value, but as it is an object, it is truthy.Misjudge
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.Uralite
@Uralite null isn't an object. See this.Petta
@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.Uralite
S
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

Sampan answered 29/7, 2011 at 18:6 Comment(0)
D
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. =)

Dicarlo answered 27/4, 2014 at 19:26 Comment(0)
S
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
}
Skit answered 7/12, 2015 at 4:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.