Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 423
Bill Avatar asked Jul 29 '11 18:07

Bill


2 Answers

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

like image 188
Raynos Avatar answered Oct 12 '22 23:10

Raynos


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

like image 43
marc Avatar answered Oct 13 '22 00:10

marc