Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Number('') returns 0 whereas parseInt('') returns NaN

Tags:

javascript

I have gone through similar questions and answers on StackOverflow and found this:

parseInt("123hui")
returns 123

Number("123hui")
returns NaN

As, parseInt() parses up to the first non-digit and returns whatever it had parsed and Number() tries to convert the entire string into a number, why unlikely behaviour in case of parseInt('') and Number('').

I feel ideally parseInt should return NaNjust like it does with Number("123hui")

Now my next question:

As 0 == '' returns true I believe it interprets like 0 == Number('') which is true. So does the compiler really treat it like 0 == Number('') and not like 0 == parseInt('') or am I missing some points?

like image 949
ABGR Avatar asked Dec 15 '15 06:12

ABGR


People also ask

Why is parseInt return NaN?

If the first character cannot be converted to a number with the radix in use, parseInt returns NaN . Leading whitespace is allowed. For arithmetic purposes, the NaN value is not a number in any radix. You can call the Number.isNaN function to determine if the result of parseInt is NaN .

What does parseInt return?

parseInt() method parses a string argument and returns an integer of the specified radix or base.

Can parseInt return undefined?

Try replacing your return with return decimalnum; -- you may still be returning undefined. parseInt is not for rounding - it actually takes the integer component of a number, or coerces a string to be a number. If you want to round, use Math.


1 Answers

The difference is due in part to Number() making use of additional logic for type coercion. Included in the rules it follows for that is:

  • A StringNumericLiteral that is empty or contains only white space is converted to +0.

Whereas parseInt() is defined to simply find and evaluate numeric characters in the input, based on the given or detected radix. And, it was defined to expect at least one valid character.

13) If S contains a code unit that is not a radix-R digit, let Z be the substring of S consisting of all code units before the first such code unit; otherwise, let Z be S.

14) If Z is empty, return NaN.

Note: 'S' is the input string after any leading whitespace is removed.


As 0=='' returns true I believe it interprets like 0==Number('') [...]

The rules that == uses are defined as Abstract Equality.

And, you're right about the coercion/conversion that's used. The relevant step is #6:

If Type(x) is Number and Type(y) is String,
return the result of the comparison x == ToNumber(y).

like image 179
Jonathan Lonowski Avatar answered Oct 19 '22 17:10

Jonathan Lonowski