Skip to main content
Mohammad Shehadeh — home (MSH monogram, letter M filled with the Palestinian flag)

Type coercion in JavaScript

Published on
2 min read

Type coercion is the automatic conversion of a value from one data type to another. It happens during operations or comparisons that mix different data types.

Implicit vs Explicit Type Coercion

  • Implicit Type Coercion:

    Happens automatically during operations.
    Example: 5 + '5'

  • Explicit Type Coercion:

    You convert manually with functions like Number(), String(), and so on.
    Example: Number('10') converts the string to a number.

Number to String Coercion

1const num = 99;
2const str = '10' + num; // coercion: number to string
3console.log(str); // 1099

JavaScript coerces the number 99 into a string, then concatenates the two values into the string 1099.

String to Number Coercion

1const num = 99;
2const str = num - '10'; // coercion: string to number
3console.log(str); // 89

Here the string 10 is coerced into a number, giving 89.

Equality Comparison Coercion

1console.log([] == ![]); // true

Let's break it down.

  • [] is truthy, and ! negates a truthy value, so ![] evaluates to false.

  • Now we have [] == false.

    • Per the ECMAScript® Language Specification: if Type(y) is Boolean, return the result of the comparison ToNumber(x) == y.
  • So the expression becomes [] == 0, since JavaScript coerces false to 0.

    • Per the ECMAScript® Language Specification: if Type(x) is Object and Type(y) is either String or Number, return the result of the comparison ToPrimitive(x) == y.
  • [].toString() is '', which leaves us at '' == 0. JavaScript coerces '' to 0.

  • Finally, 0 == 0 is true.

Whenever two values are compared with the == operator, JavaScript runs the Abstract Equality Comparison Algorithm.

Quick Recap

  1. Type Coercion Types

    • Implicit: Automatic conversion during operations
    • Explicit: Manual conversion using functions
    • Context-dependent behavior
    • Operator-specific rules
  2. Common Coercion Patterns

    • String concatenation with numbers
    • Mathematical operations with strings
    • Boolean comparisons
    • Object to primitive conversion
  3. Best Practices

    • Use strict equality (===) when possible
    • Be explicit with type conversions
    • Understand operator precedence
    • Test edge cases thoroughly

References

Related Articles

GET IN TOUCH

Let's work together

I build fast, accessible, and delightful digital experiences for the web. Whether you have a project in mind or just want to connect, I'd love to hear from you.

Get in touch

or reach out directly at hello@mohammadshehadeh.com