Type Coercion

In certain contexts, JavaScript will automatically convert a value to another data type before it evaluates some statement. This implicit conversion is called type coercion.

Boolean Context

When a non-boolean value is used in a boolean context, JavaScript will apply the same rules as the Boolean function to implicitly convert the value.

Coercion to boolean commonly occurs for

  • the condition of an if statement
  • the first operand of the ternary operator ?
  • the operand of the logical NOT operator !
  • the operands of the logical AND && and OR || operators (the result of the expression is one of the operands, not necessarily a boolean)
const num = 0;
if (num) {
  // this block is NOT executed because 0 is falsy
}

String Context

If the addition operator + is used for primitive values and one operand is a string, the other one will be coerced into a string as well. The conversion logic is the same as when using the String function. Afterwards, the two strings are concatenated.

let name;
'hello ' + name;
// => 'hello undefined'

Numeric Context

Many operators coerce the operands into numbers (if necessary) according to the logic of the Number function explained above.

  • Arithmetic operators: + (if no string is involved), -, *, /, %, **
  • Unary plus and unary negation operators: +, -
  • Relational operators (for non-string operands): >, >=, <, <=
  • Bitwise operators: |, &, ^, ~

Refer to the MDN list of operators for more details about any of those operators.

To avoid mistakes, it is good practice to always call Number explicitly before applying those operators.

Learn More


References: