0

why these two code has different answers:

code 1 answer is false code 2 answer is true

code 1

var x = Boolean (false);
if (x) 
{
      console.log (true);
}
else 
{
      console.log (false);
}
// answer is false

code2

var x = new Boolean (false);
if (x)
{
     console.log (true);
}
else 
{
     console.log (false);
}

//answer is true 

2 Answers2

1

Any object whose value is not undefined or null, including a Boolean object whose value is false, evaluates to true when passed to a conditional statement.

From https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Boolean

The global function Boolean() can be used for type casting when called without new, eg

var foo = Boolean(param); // equivalent to `var foo = !!param`

When called with new, a wrapper object will be created additionally, which means that you can assign arbitrary properties to the object:

var foo = new Boolean(param); // equivalent to `var foo = Object(Boolean(param));`
console.log(foo === true) // true, because object - true
foo.prop1 = 'test';
yurzui
  • 205,937
  • 32
  • 433
  • 399
1

The first block omits the "new" keyword, x is assigned the value of Boolean(expr), which is a function that converts a non-boolean value to a boolean one.

The second block creates a Boolean object, the if conditional returns true because x is not undefined.

Michael Xu
  • 141
  • 3