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 255as 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 0will 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.

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 .

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.

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.

Programming, project management and politics

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store