laurent
laurent

Reputation: 90804

Why is this boolean casting not working as expected?

I've just answered this question but I don't understand why it works the way it does.

Basically the problem can be simplified to this:

var b = new Boolean(false);
console.info(b == false); // Prints "true" - OK
console.info(b && true); // Prints "true" - but should be "false"

I assume there's some unintuitive automatic casting going on but I don't understand it would sometime be automatically casted to true, sometime to false. Any idea?

I guess this illustrates the problem better:

> false && 123

false // OK 

> new Boolean(false) && 123

123   // ???

Upvotes: 2

Views: 169

Answers (4)

Pete D
Pete D

Reputation: 837

Maybe the object b is true when doing (b && false) but doing to logical operation of true and false results to false.

If you do this:

var b = new Boolean(false);
console.info(b == false); // Prints "true" - OK
console.info(b && true); // Prints "true"

So even though the object b was set to false in the (b && true) it results to true because it exists and it's not set to null.

Upvotes: 0

Esailija
Esailija

Reputation: 140228

== does a lot of coercion:

Object == false =>
Object == 0 =>
Object.valueOf() == 0 =>
false == 0 =>
0 == 0 =>
true

Or if you follow the steps in the algorithm, it is

Step 7, Step 9, Step 6, Step 1 c iii.

The logical and just goes directly for ToBoolean, which always returns true for objects.

Note that new Boolean returns an object and not a boolean value.

Upvotes: 2

basilikum
basilikum

Reputation: 10536

I'm not sure if I understand your question correctly but it look like the major issue derives from the fact that if (new Boolean(false)) evaluates to true. If you put expressions in an if statement or link them with logical operators (i.e. &&), JavaScript only checks if they are truthy or falsy. When it comes to boolean primitives, it is easy:

true -> truthy
false -> falsy

But when it comes to boolean objects, it looks different:

new Boolean(false) -> truthy
new Boolean(true) -> truthy

The reason for this is, that in JavaScript, every object (if not null) is truthy.

Upvotes: 0

JTravakh
JTravakh

Reputation: 166

False AND False is false. Truth tables - AND only returns true if both arguments are true, and neither is in this case.

EDIT: True AND False is also false, so anything && False is false.

Upvotes: 0

Related Questions