How to convert between types

Inspect a value's type

The typeof operator identifies common primitive types. Arrays need Array.isArray.

console.log(typeof "42");       // string
console.log(typeof 42);         // number
console.log(typeof true);       // boolean
console.log(Array.isArray([])); // true

Convert to a number

Number converts a complete value. Validate the result because invalid text becomes NaN.

const input = "42";
const amount = Number(input);
if (Number.isNaN(amount)) {
  console.log("Enter a valid number");
} else {
  console.log(amount + 8);
}

Convert to text or boolean

String gives a text representation. Boolean applies truthy and falsy rules, so the non-empty string "false" is true.

console.log(String(250));       // "250"
console.log(Boolean(1));        // true
console.log(Boolean(0));        // false
console.log(Boolean("false"));  // true

Avoid accidental coercion

The plus operator concatenates when either operand is a string, while other arithmetic operators often coerce to numbers. Convert at input boundaries.

console.log("5" + 2);         // "52"
console.log("5" - 2);         // 3
const quantity = Number("5");
console.log(quantity + 2);     // 7