JavaScript: parseInt() vs Number()

Emre Avcılar
2 min readSep 11, 2023

--

This is an issue that I see in projects. In this article, I will explain why you should use Number() instead of parseInt().

You need a variable that contains a number, which comes from a form, an API, etc. and you convert it like this;

const outputNumber = "13";

if(parseInt(outputNumber, 10) === 13){
// do something
}

This code works, but the way you choose to convert is inefficient. You should use Number() instead of parseInt().

const outputNumber = "13";

if(Number(outputNumber) === 13){
// do something
}

But why? What’s the difference between Number() and parseInt()?

Performance:

Just to measure it; let’s do a simple benchmark that measures both Number() and parseInt(). For it, I will create a function that iterates 150 million times, function will take a callback parameter. I will call it with both Number() and parseInt() functions.

function benchmark(name, cb) {
const t0 = performance.now()
for (let i = 0; i < 15e7; i++) {
cb();
}
const t1 = performance.now()
console.log(`${name} took ${t1 - t0} ms`);
}

const process1 = () => Number('9.9'); // 9.9
const process2 = () => parseInt('9.9', 10); // 9
const process3 = () => Number('12'); // 12
const process4 = () => parseFloat('12'); // 12

benchmark('process1', process1); // 94.5 ms
benchmark('process2', process2); // 651.59 ms
benchmark('process3', process3); // 656.5 ms
benchmark('process4', process4); // 798.29 ms
benchmark of number and parseInt

Let’s make some additional benchmarks that also include parseFloat and type coercion

function benchmark(name, cb) {
const t0 = performance.now()
for (let i = 0; i < 15e7; i++) {
cb();
}
const t1 = performance.now()
console.log(`${name} took ${t1 - t0} ms`);
}

const process1 = () => Number('15');
const process2 = () => parseInt('15', 10);
const process3 = () => parseFloat('15');
const process4 = () => +'15';

benchmark('process1', process1); // 94.70 ms
benchmark('process2', process2); // 651.5 ms
benchmark('process3', process3); // 764.69 ms
benchmark('process4', process4); // 668.79 ms

So where should we use parseInt()?

Of course, there are some other cases that are beneficial to using the parseInt(). For instance, if you want to convert a string with pixels and you only need the number value, then you should use parseInt(). In that case, Number() returns NaN.

console.log(parseInt('5px')) // output 5
console.log(Number('5px')) // output NaN

If you like this article share and clap 👏 👏. Thanks!

--

--