1

Possible Duplicate:
Why does !new Boolean(false) equals false in JavaScript?

var b = new Boolean(null);


alert(b instanceof Boolean);

 if(b) {
    alert('cv');
    alert(b.toString());
 }

Why if code block is executed? Is b supposed to be a boolean type and evaluated as false?

Please explain thanks

Community
  • 1
  • 1
David He
  • 394
  • 1
  • 6
  • 16
  • new Boolean, new Number and new String should never be used in practical javascript. It's kinda like you wouldn't use `==` to compare strings in java, you wouldn't use `new String` in javascript because `new String("asd") == new String("asd") //false` but `"asd" == "asd" //true` same for new Boolean and new Number – Esailija Jan 11 '13 at 22:42

2 Answers2

2

The code block executes, because the object exists and is not undefined although it has no value currently. The point of the Boolean object in javascript is to convert non-boolean objects to the "true" or "false" value.

if you have

if( b.valueOf() );

that will evaluate the actual value of the object.

1

All objects are truthy, except null. Therefore, even if you write new Boolean(false) specifically, it will still be truthy.

This is why you never write new Boolean. To cast to a boolean, just use !!

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592