Type Conversion
Convert values between strings, numbers and booleans.
Syntax
Number(value)
String(value)
Boolean(value)Sometimes you need to convert a value from one type to another.
Common conversions
Number('5')converts a string to a number.String(5)converts a number to a string.Boolean(value)converts to true/false.
JavaScript also converts types automatically in some situations — for example '5' + 1 becomes '51' because + with a string joins text.
Example
Loading editor…
Press Run to execute the code.
When to use it
- Parse a price entered in a text input as a number before performing arithmetic in a checkout form.
- Convert an integer status code to a string to concatenate it into a log message.
- Coerce a truthy/falsy API response field into a strict boolean for conditional rendering.
More examples
String input to number
Converts a string from a text input to a number with Number() so arithmetic works correctly.
const input = "42.5";
const price = Number(input);
console.log(price + 7.5); // 50 – arithmetic, not concatenationNumber to string conversion
Uses String() to explicitly convert a number to a string before concatenating it into a message.
const statusCode = 404;
const message = "Error " + String(statusCode) + " – Not Found";
console.log(message);Boolean conversion with Boolean()
Demonstrates Boolean() conversion, showing which values are falsy (0, empty string, null).
console.log(Boolean(0)); // false
console.log(Boolean("")); // false
console.log(Boolean("hello")); // true
console.log(Boolean(null)); // false
Discussion