JavaScript Basics: parseInt() vs Number and when to use each one
When you want to convert a variable from a string to a number you have two options that perform the same operation but behave differently from one another. So this blog will go over the similarities and differences between using the parseInt() function and Number() a wrapper function that returns a number.
parseInt()
The parseInt()
function parses a string argument and returns an integer of the specified radix. The function will return a string of the passed in value or NaN (Not a Number) when the radix is smaller than 2 or greater than 36 or the first non-whitespace character cannot be converted to a number. Below is a few examples of using parseInt():
function roughScale(x, base) {
const parsed = parseInt(x, base);
if (isNaN(parsed)) { return 0; }
return parsed * 100;
}console.log(roughScale(' 0xF', 16));
// expected output: 1500console.log(roughScale('321', 2));
// expected output: 0// all functions below return 15
parseInt('0xF', 16)
parseInt('F', 16)
parseInt('17', 8)// returns NaN
parseInt('Hello', 8) // Not a number at all
parseInt('546', 2) // Digits other than 0 or 1 are invalid for binary radix
Number()
Number
is a primitive wrapper object used to represent and manipulate numbers like 37
or -9.25
.
The Number
constructor contains constants and methods for working with numbers. Values of other types can be converted to numbers using the Number()
function.
When used as a function, Number(value)
converts a string or other value to the Number type. If the value can't be converted, it returns NaN
. Below is a few examples:
Number('123') // returns the number 123
Number('123') === 123 // trueNumber("unicorn") // NaN
Number(undefined) // NaN