Explanation of how parseInt works in JavaScript


What is parseInt and what is it used for in programming? I checked this page: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt and it is not clear to me since I apply it on the console.


parseInt() is a high-level function used to parse a string and try to obtain a numeric value from it.

By trying I mean the following:

A string that is obviously a number is easily obtainable as a number . Example:

 var s = "1234"; var n = parseInt(s); console.log(n); // 1234

Of course also accept negatives

 var s = "-1234"; var n = parseInt(s); console.log(n); // -1234

However a string that does not represent a number like the following

    var s = "5678EstoYaNoEsNumero";
    var n = parseInt(s);
    console.log(n); // 5678

It also obtains a valid value, which corresponds to the number resulting from converting the digits as far as possible to number.

This behavior is ideal for example in text fields when there may be blank spaces before or after example:

 var s = " 4321 "; var n = parseInt(s); console.log(n); // 4321

When the parse can no longer obtain any number, it stops even if there are more digits later, so in this case the parse will return NaN which means that it could not obtain a valid value. Example:

        var s = "   abc8765  ";
        var n = parseInt(s);
        console.log(n); // NaN

But it not only allows parsing strings in base 10, for example the following is also valid in hexadecimal base

var sHexa = "0xDEAD";
var nHexa = parseInt(sHexa);
console.log(nHexa); // 57005

Finally, if you want to parse a string in another base, you can indicate it with the second argument of the function, for example to parse a binary string:

var sBin = "10101010";
var nBin = parseInt(sBin, 2);
console.log(nBin); // 170
Scroll to Top