What is the difference between parseInt() and Number()? What is the difference between parseInt() and Number()? javascript javascript

What is the difference between parseInt() and Number()?


Well, they are semantically different, the Number constructor called as a function performs type conversion and parseInt performs parsing, e.g.:

// parsing:parseInt("20px");       // 20parseInt("10100", 2);   // 20parseInt("2e1");        // 2// type conversionNumber("20px");       // NaNNumber("2e1");        // 20, exponential notation

Also parseInt will ignore trailing characters that don't correspond with any digit of the currently used base.

The Number constructor doesn't detect implicit octals, but can detect the explicit octal notation:

Number("010");         // 10Number("0o10")         // 8, explicit octalparseInt("010");       // 8, implicit octalparseInt("010", 10);   // 10, decimal radix used

And it can handle numbers in hexadecimal notation, just like parseInt:

Number("0xF");   // 15parseInt("0xF"); //15

In addition, a widely used construct to perform Numeric type conversion, is the Unary + Operator (p. 72), it is equivalent to using the Number constructor as a function:

+"2e1";   // 20+"0xF";   // 15+"010";   // 10


typeof parseInt("123") => numbertypeof Number("123") => numbertypeof new Number("123") => object (Number primitive wrapper object)

first two will give you better performance as it returns a primitive instead of an object.


If you are looking for performance then probably best results you'll get with bitwise right shift "10">>0. Also multiply ("10" * 1) or not not (~~"10"). All of them are much faster of Number and parseInt.They even have "feature" returning 0 for not number argument.Here are Performance tests.