0

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.

1
  • .parseInt() function actually only parse string variables. Here you're giving a boolean. Commented May 20, 2016 at 10:56

3 Answers 3

4

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).

Sign up to request clarification or add additional context in comments.

Comments

4

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

enter image description here

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.