fruitjs
fruitjs

Reputation: 765

Type conversion of Boolean to Number in JavaScript

I was working on type conversion of Boolean values to Number in javascript.

console.log(new Number(true));//Prints 1
console.log(+true);//Prints 1
console.log(parseInt(true));//Prints NaN

Why is the parseInt is throwing NaN? While first and second case given above are working fine.

Upvotes: 0

Views: 1420

Answers (3)

gurvinder372
gurvinder372

Reputation: 68413

Number constructor invokes toNumber internally which as per spec

Boolean - Return 1 if argument is true. Return +0 if argument is false.

Which means Number(true) returns 1.

However, parseInt invokes toString internally and as per spec

Boolean
If argument is true, return "true".

If argument is false, return "false".

Which means parseInt(true) -> parseInt("true") -> NaN

since as per spec again

  1. If number is NaN, +0, −0, +∞, or −∞, return +0.

Hope this helped.

Upvotes: 2

Starfish
Starfish

Reputation: 3574

If you are actually working on number conversions then this table might be very helpful:

enter image description here

Upvotes: 3

Nina Scholz
Nina Scholz

Reputation: 386680

Because parseInt expects a string and 'true' is NaN.

From MDN:

parseInt()

The parseInt() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).

Upvotes: 4

Related Questions