Amir Nassaji
Amir Nassaji

Reputation: 25

differences between Boolean answers in javascript

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 

Upvotes: 0

Views: 43

Answers (2)

yurzui
yurzui

Reputation: 214017

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';

Upvotes: 1

Michael Xu
Michael Xu

Reputation: 141

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.

Upvotes: 1

Related Questions