javascripttype-conversion

Best way to parse an int in Javascript


One can convert a string to an integer in numerous ways, e.g.

I assume the first is the canonical form, but e.g. uses the third one to coerce ints. There are probably more ways to do it.

What are the differences and benefits of using each of these? Which is expected to be the fastest?


Solution

  • The canonical way to parse a decimal int is parseInt(str, 10).

    Regarding other solutions :

    You should not use another solution than parseInt(str,10) if you don't need to ensure the string contains nothing else than an int. That's the fastest solution and, more importantly, the most readable. If a JS engine does some optimizations, there is no reason for other solutions to get faster than this one.