newswim
newswim

Reputation: 450

why does true * true === 1 in JS?

Going through Good Parts and messing around in node, I'm wondering why this behavior occurs. I know that ! refers to the "logical not" operator, and that !! basically booleanates(ifies?) the returned value of !x, but why this?

var x = 3, y = 4;

x != y;     // true
x = !y      // false ----> But really, its setting x to "not y", a truthy value, correct
x = !!x*x   // 1 --- wut?

So, after playing with it a bit, I understand that what's being declared is, "x equals not not x ("true" since !x === false) times x (true)"

So I guess the question is, why is true * true === 1 in JS?

Upvotes: 4

Views: 388

Answers (2)

Mike Horstmann
Mike Horstmann

Reputation: 588

While false is a bit value of 0, True is a bit value of 1. So I believe what you are asking is why does 1 * 1 = 1 ? I hope that explains it well enough.

Upvotes: 1

Luke Eller
Luke Eller

Reputation: 627

The * operator would coerce true to 1 for the purposes of evaluating the multiplication, and 1 * 1 === 1.

Upvotes: 4

Related Questions