Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Why true/true is 1, true/false is Infinity, false/true is 0 and false/false is NaN?

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.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Why true/true is 1, true/false is Infinity, false/true is 0 and false/false is NaN?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×