In JavaScript, it’s common to need to convert values between strings and numbers, for example when working with user input or when manipulating data. It can be accomplished using various built-in functions and methods, such as parseInt()
, parseFloat()
, Number()
constructor, and toString()
.
However, it’s important to be aware of the potential pitfalls of conversion, such as non-numeric input, decimal precision, and numeric overflow, and to use the appropriate conversion method for your particular use case.
In JavaScript, string
and number
are two of the primitive types, which means they are immutable values that can be represented directly at the lowest level of the language.
The string type is used to represent and manipulate a sequence of characters. You can use single quotes, double quotes, or backticks to create string literals.
const str1 = 'Hello';
const str2 = "World";
const str3 = `Hello World`;
The number type is used to represent numeric values. You can use decimal, hexadecimal, octal, or binary literals to create number literals.
const num1 = 42;
const num2 = 0x2A;
const num3 = 0o52;
const num4 = 0b101010;
Both string and number have their corresponding object wrapper types, which are String and Number. These are objects that provide useful methods and properties for working with the primitive values.
// Primitive types
let stringPrimitive = 'hello';
let numberPrimitive = 123;
console.log(typeof stringPrimitive); // "string"
console.log(typeof numberPrimitive); // "number"
// Wrapper types
let stringWrapper = new String('hello');
let numberWrapper = new Number(123);
console.log(typeof stringWrapper); // "object"
console.log(typeof numberWrapper); // "object"
When you access a property or a method on a primitive value, JavaScript automatically wraps the value into the corresponding object wrapper and then accesses the property or method on the object. However, this is only a temporary conversion and does not change the original value.
You can also use the String() constructor and Number() constructor to create string and number objects explicitly, but this is not recommended as it can cause confusion and unexpected behavior when comparing values or passing them to functions that expect primitive types.
In JavaScript, there are several special values that can be represented by the Number
type. These values are often used to indicate the absence of a meaningful number, or to represent values that cannot be expressed as finite numbers.
The special number values in JavaScript are:
NaN
(Not a Number): This is a special value that indicates that a value is not a valid number, returned when a mathematical operation is performed on an undefined or unrepresentable value, such as dividing zero by zero or taking the square root of a negative number.Infinity
and -Infinity
: These values represent positive and negative infinity, respectively. They are returned when a number exceeds the maximum or minimum representable value.-0
(Negative zero): This is a special value that represents zero with a negative sign. -0
is returned when dividing a negative number by zero.It’s important to note that NaN
is not equal to any other value, including itself. This means that you cannot use the ==
or ===
operators to check for NaN
. Instead, you can use the isNaN()
function to check whether a value is NaN
. Also, Infinity
and -Infinity
are not considered equal to each other or any other value except themselves.
Here are some examples of using these special number values in JavaScript:
let x = 10 / "hello"; // returns NaN
let y = 1 / 0; // returns Infinity
let z = -1 / 0; // returns -Infinity
let a = -0; // represents negative zero
console.log(isNaN(x)); // true
console.log(isNaN(y)); // false
console.log(Infinity === Infinity); // true
console.log(-Infinity === -Infinity); // true
console.log(Infinity === -Infinity); // false
console.log(1 / -0); // returns -Infinity
console.log(-1 / 0); // returns -Infinity
console.log(1 / 0); // returns Infinity
When converting strings to numbers in JavaScript, there are a few things to keep in mind: type coercion, valid number, radix, and locale. There are several ways to convert a string to a number in JavaScript:
Number()
constructorUsing Number()
constructor is preferred as it converts any value to a number primitive, which is easier to work with and compare.
const num1 = Number(42); // converts 42 to a number primitive
const num2 = Number(42); // converts 42 to a number primitive
console.log(num1 == num2); // true, because they are the same value and type
console.log(num1 === num2); // true, because they are the same value and type
Remember using new Number()
will create a number object instead. This is not recommended as it can cause confusion and unexpected behavior when comparing values or passing them to functions that expect primitive types.
const num1 = new Number(42); // creates a number object
const num2 = new Number(42); // creates another number object
console.log(num1 == num2); // false, because they are different objects
console.log(num1 === num2); // false, because they are different objects
parseInt()
or Number.parseInt()
functionsThe parseInt()
function is a global function that parses a string argument and returns an integer of the specified radix or base. The Number.parseInt()
method is a static method of the Number object that has the same functionality as the global parseInt()
function. It was introduced in ES6 to modularize the global functions.
parseInt("42"); // 42
parseInt("42", 10); // 42 in decimal
Number.parseInt("42", 16); // 66 in hexadecimal
Number.parseInt("42", 2); // NaN, because 42 is not a valid binary number
The parseFloat()
function is a global function that parses a string argument and returns a floating-point number. The Number.parseFloat()
method is a static method of the Number object that has the same functionality as the global parseFloat()
function. It was introduced in ES6 to modularize the global functions.
parseFloat("3.14"); // 3.14
parseFloat("42.0"); // 42
Number.parseFloat("3.14abc"); // 3.14, ignores the trailing characters
Number.parseFloat("abc3.14"); // NaN, cannot parse the string
The unary plus operator (+) is a shorthand way to convert a string to a number in JavaScript. It works by applying the Number()
function to the operand.
+"42"; // 42
+"3.14"; // 3.14
+"0xF"; // 15, hexadecimal notation
+"0o10"; // 8, octal notation
+"0b101010"; // 42, binary notation
+true; // 1
+false; // 0
+null; // 0
+undefined; // NaN
+"Hello"; // NaN
+"3.14abc"; // NaN
+""; // NaN
When converting numbers to strings in JavaScript, there are a few things to keep in mind: rounding errors, loss of precision, radix, padding, and localization. There are several ways to convert numbers to strings in JavaScript:
toString()
methodThe toString()
method is a method that returns a string representation of an object. It is inherited by every object that is derived from the Object prototype. It can be used to convert a number, a boolean, a date, an array, or any other object to a string.
The toString()
method can take an optional argument called a radix, which specifies the base of the number to be converted.
const num = 42;
num.toString(); // "42"
num.toString(2); // "101010"
num.toString(16); // "2a"
String()
constructorUsing String()
constructor to convert a number to a string is different from using new String()
to create a string object. The former returns a primitive string value, while the latter returns an object wrapper for the string.
const num = 42;
const str1 = String(num); // converts 42 to a primitive string
const str2 = new String(num); // creates a string object for 42
console.log(typeof str1); // "string"
console.log(typeof str2); // "object"
You can use the template literals to convert a number to a string. Template literals are string literals that allow embedded expressions. You can use the ${}
syntax to insert a number into a string.
const num = 42;
const str = `The number is ${num}.`; // "The number is 42."
The concatenation operator (+) is an operator that can be used to join two or more strings together. It can also be used to convert a number to a string by adding an empty string to it. The concatenation operator (+) is different from the unary plus operator (+), which is a shorthand way to convert a string to a number.
const num = 42;
const str = num + ""; // "42"
Here are some potential pitfalls to keep in mind when converting between strings and numbers in JavaScript:
When converting a string to a number, it’s important to ensure that the input string contains only numeric characters. If the string contains non-numeric characters, the conversion may result in NaN
(Not a Number).
parseInt('hello') // NaN
Number('3.14hello') // NaN
To avoid this issue, you can use the isNaN()
function to check if a value is NaN, or use regular expressions to ensure that the input string only contains numeric characters.
When converting a string to a floating-point number, it’s important to be aware of potential rounding errors and loss of precision.
parseFloat('0.1') + parseFloat('0.2') // 0.30000000000000004
To avoid this issue, you can use a library like decimal.js
or big.js
to perform arbitrary-precision arithmetic, or use the toFixed()
method to specify the number of decimal places to include in the result.
When converting a string to a number, it’s important to be aware of the maximum and minimum values that can be represented by JavaScript’s numeric data type. If the input string represents a number that is outside the range of valid values, the conversion may result in Infinity
or -Infinity
.
parseInt('9999999999999999') // 10000000000000000
Number.MAX_VALUE + 1 // Infinity
To avoid this issue, you can check if the input string is within the valid range of values before performing the conversion, or use a library that supports arbitrary-precision arithmetic.
Overall, it’s important to use the appropriate conversion method for your particular use case, and to be aware of potential issues that may arise when converting between strings and numbers. By understanding these potential pitfalls and using appropriate conversion methods and libraries, you can ensure that your code works correctly and efficiently.