MSH

Type coercion in JavaScript

Published on

Type coercion refers to the automatic conversion of values from one data type to another, typically performed during operations or comparisons involving different data types.

Implicit vs Explicit Type Coercion

  • Implicit Type Coercion:

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

  • Explicit Type Coercion:

    Involves manual conversion using functions like Number(), String(), etc.
    Example: Number('10') explicitly 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 has coerced the 99 from a number into a string and then concatenated the two values together, resulting in a string of 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 numeric value, resulting in a number of 89.

Equality Comparison Coercion

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

let's take a minute to break it down

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

  • Now, we have [] == false

    • According to ECMAScript® Language Specification - If Type(y) is Boolean, return the result of the comparison ToNumber(x) == y.
  • So, the expression becomes [] == 0 in this case JavaScript coerces false to 0.

    • According to 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.
  • Therefore, [].toString() is '' which leave us at '' == 0 JavaScript coerces '' to 0

  • Finall, 0 == 0 is true

This is interesting, isn't it? Whenever 2 values are compared using == operator, JavaScript performs the Abstract Equality Comparison Algorithm.

Key Takeaways

  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

GET IN TOUCH

Let's work together

I build exceptional and accessible digital experiences for the web

WRITE AN EMAIL

or reach out directly at hello@mohammadshehadeh.com