JavaScript Type Conversion and Coercion
Type conversion changes a JavaScript value from one data type to another. Use explicit conversion when you want predictable results, and learn to recognize the automatic conversions called coercion.
Quick answer: call Number(value), String(value) or Boolean(value) to convert a value intentionally. Coercion happens when JavaScript converts values automatically during an operation.
Convert values explicitly
JavaScript provides global functions for common conversions. A string containing a valid number can become a number; String() creates text, and Boolean() checks a value's truthiness.
const quantity = Number("4");
const label = String(quantity);
const hasLabel = Boolean(label);
console.log(quantity); // 4
console.log(label); // "4"
console.log(hasLabel); // true
Number("four") returns NaN because the text is not a number. A useful check is Number.isFinite(value) after conversion.
Be careful when converting form input
A form control's value is text, even when it looks like a number. Check for an empty value before converting: Number("") returns 0, which may not mean what your form intends.
const rawValue = "12";
const amount = Number(rawValue);
if (rawValue.trim() !== "" && Number.isFinite(amount)) {
console.log(amount * 2); // 24
}
Use parseInt(text, 10) only when you specifically want an integer from the start of a string. For a complete numeric value, Number() is often clearer.
Recognize automatic coercion
JavaScript may convert an operand to make an operation possible. This is called type coercion. For example, + can join a string and a number, while subtraction converts numeric text to a number.
console.log("5" + 2); // "52"
console.log("5" - 2); // 3
When the result is meant to be numeric, convert the input explicitly first. For equality checks, prefer === and !== so the comparison does not coerce the values.
How do booleans work in a conversion?
Empty strings, 0, false, null and undefined convert to false. Non-empty strings convert to true—including the text "false" and "0". If an input field contains the words true or false, compare the text explicitly instead of using Boolean(text).
Continue learning
Review operators and expressions to understand how coercion can affect calculations, or use form validation to check user input before processing it.
For another reference, see the W3Schools JavaScript type conversion guide.