Type Conversion

Convert values between strings, numbers and booleans.

SyntaxNumber(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

Try it yourself
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.

Example · js
const input = "42.5";
const price = Number(input);
console.log(price + 7.5); // 50 – arithmetic, not concatenation

Number to string conversion

Uses String() to explicitly convert a number to a string before concatenating it into a message.

Example · js
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).

Example · js
console.log(Boolean(0));         // false
console.log(Boolean(""));        // false
console.log(Boolean("hello"));   // true
console.log(Boolean(null));      // false

Discussion

  • Be the first to comment on this lesson.