Type Conversions in JavaScript: Converting Strings to Numbers
There are various ways to convert strings into numbers in JavaScript. We have built-in functions, like parseInt
and Number
that we can use:
parseInt('42'); // Returns 42
Number('42'); // Returns 42
Both functions return the number equivalent. So the question comes: What is the difference between parseInt
and Number
, if there's any?
The Difference Between parseInt and Number
While the Number
function simply converts the string into a number, parseInt
also uses a second optional argument, a radix. It specifies which numeral system to use. It can be an integer between 2 and 36. By default, we want this to be set to 10 but it is not a default value, so it is recommended to set it explicitly.
parseInt('42', 6); // Returns 26
parseInt('42', 10); // Returns 42
parseInt('42', 36); // Returns 146
Notice that based on the radix, parseInt
will return different values. The Number
function on the other hand can work on other values as well, not just on strings:
Number(true); // Returns 1
Number(false); // Returns 0
Number(['10']); // Returns 10
Number([1, 2]); // Returns NaN
Note that when using arrays, it will only work with a single element. When Number
cannot convert the input value into a number, it will return NaN
.
Converting Numbers to Strings
Of course, we can reverse these and convert numbers back to strings, using the String
function:
Number('42'); // Returns 42
String(42); // Returns '42'
But there is an even shorter solution since JavaScript is weakly typed. This means we can convert the two types into one another using a plus sign. It will turn a string into a number:
+'42' // Results in 42
42 + '' // Results in '42'
As you can see, this works the other way around too. We can convert a number into a string, by simply appending an empty string to the number. Which one to use? It depends on which one you prefer, but make sure you stick with one to stay consistent. For readability, I prefer using the Number
object, as it doesn't require a radix. Therefore, it is more reliable even for inexperienced developers.
Resources:
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: