0

Why the following if statement evaluates to true since the value is false?

var x = new Boolean(false);
if (x) {
  // this code is executed
}

from: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean

  • possible duplicate of [What is the purpose of new Boolean() in Javascript?](http://stackoverflow.com/questions/856324/what-is-the-purpose-of-new-boolean-in-javascript) –  Jul 29 '15 at 07:59
  • 2
    All objects are true. – melpomene Jul 29 '15 at 07:59

2 Answers2

3

It does'nt evaluate to false, since it is an object. the Value of x is an object resulting out of the constructor function:

Boolean {[[PrimitiveValue]]: false}

Objects are allways truthy. instead try grabbing the actual value from your constructed object:

if(x.valueOf()){}

hope this helped

Max Bumaye
  • 1,017
  • 10
  • 17
  • this would not work in this case though. The questioneer has created an Object from a constructor function an {} === true be falsy – Max Bumaye Jul 29 '15 at 08:05
  • i did. var test = new Boolean(true); test === true results in falsy return – Max Bumaye Jul 29 '15 at 08:25
  • === DOESNT coerce you mean == ... it works for == but coercing is kind of "unpredictable" (it in fact isnt unpredictable but reading the code it may get confusing) so you should not do it. I dont really get why he is using a constructor function to return a boolean anyway – Max Bumaye Jul 29 '15 at 08:26
1

Because x has become an object, which is a truthy value (i.e not false).

try:

var x = false;
if (x) {
  // this code will not be executed 
} else {
  // this code will be executed instead
}

Be very careful with your types ;)

MrHaze
  • 3,786
  • 3
  • 26
  • 47