Reputation: 765
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
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
- If number is NaN, +0, −0, +∞, or −∞, return +0.
Hope this helped.
Upvotes: 2
Reputation: 3574
If you are actually working on number conversions then this table might be very helpful:
Upvotes: 3
Reputation: 386680
Because parseInt
expects a string and 'true'
is NaN
.
From MDN:
The
parseInt()
function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).
Upvotes: 4