Why true/true is 1, true/false is Infinity, false/true is 0 and false/false is NaN?
Problem
I am excited to find the following Javascript behavior:
$ node
> false/true
0
> false/false
NaN
> false/true
0
> true/true
1
> true/false
Infinity
Why is this happening?
My first approach is that Javascript converts false
to 0
and true
to 1
.
Is this correct? A reference from the documentation would be great.
Problem courtesy of: Ionică Bizău
Solution
You're absolutely right, the ToNumber
abstract operation converts true
to 1
and false
to positive 0
.
The specification says:
Boolean
The result is 1 if the argument is true. The result is +0 if the argument is false.
Solution courtesy of: Frédéric Hamidi
Discussion
View additional discussion.