Sitemap
Suraj Kumar

Suraj Kumar

Number() vs. parseInt()

2 min readMay 19, 2021

--

The Differences!

Number()

Number() takes an argument and tries to convert the type of the passed argument to a number. If Number function feels that the argument in no way can be converted to a number. It returns Nan. Its either all or nothing. This is the case when the argument is string. The string must contain entirely of numbers , or else the string won’t be converted.

Press enter or click to view image in full size

But, Number() returns 0,1 instead of Nan for few input arguments other than strings. Below are such cases, where Number does not return Nan.

Press enter or click to view image in full size

parseInt()

parseInt() on the other hand instead of trying to convert the entire type of the input argument to a number, parses the argument up to the first non-integer character, and returns the integers accordingly.

Press enter or click to view image in full size

But unlike Number(), parseInt() is strict when it gets special input other than character-rich strings. It directly evaluates them to NaN.

Press enter or click to view image in full size

What’s Common?

Get Suraj Kumar’s stories in your inbox

Join Medium for free to get updates from this writer.

Both Number and parseInt evaluates undefined to NaN.

Press enter or click to view image in full size

Also Number and parseInt don’t mind any amount of trailing or leading spaces present in the input string. It ignores them and performs their respective functions upon the characters.

--

--