Difference between Number and parseInt in JavaScript

While Number and parseInt may look similarly there are a few major differences that may lead to confusion and bugs. In this article we will go through the differences and explain them one by one.
First of all, let’s note that parseInt is used to parse string values into integers with given radix. The second parameter is optional. However, it’s a bad practice not to use it as this leads to errors. For example, if we pass 255
as hexadecimal value (FF
) which is prefixed with 0x
it will be correctly autodetected and parsed. Yet, octal number which are prefixed with 0
caused confusion and problems as many programmers assumed 0
will be ignored and the string will be parsed as decimal. However, since ECMAScript 5 auto-detection of octal literals was dropped which… leads to confusion if you were aware that value with leading 0
will be processed as octal! Therefore, we strongly recommend to simply add radix.
parseInt('10'); // returns 10
parseInt('0xFF'); // auto-detected hex value, returns 255
parseInt('010'); // depends on ECMAScript version, returns 10 now.parseInt('11', 8); // returns 9 as radix is 8
parseInt('11', 10); // returns 11
Number is a wrapper object that converts input values and returns… surprise, surprise: number! Similarly to parseInt it will auto-detect hexadecimal values.
However, the big difference between the two is when we pass non-numeric values, for example true
, false
, null
,undefined
or anything that may look like a number, e.g. 20px
.
parseInt(true); // NaN
Number(true); // 1parseInt(false); // NaN
Number(false); // 0parseInt(null); // NaN
Number(null); // 0parseInt(undefined); // NaN
Number(undefined); // NaNparseInt('20px'); // 20
Number('20px'); // NaNparseInt('abc'); // NaN
Number('abc'); // NaN
Lastly, we shouldn’t be surprised if we pass floating point literals to parseInt and we get… integer! We should note that parseInt doesn’t round the value but simply returns integer part only.
parseInt('15.75'); // 15
Number('15.75'); // 15.75
In this article we went through example of similarities and differences between Number and parseInt.
If you have any question or comment please leave it below.