SKIP TO MAIN
-- views

Type coercion in JavaScript

February 8, 2024

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#

const num = 99;
const str = '10' + num; // coercion: number to string
console.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#

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

Here, the string 10 is coerced into a numeric value, resulting in a number of 89.

Equality Comparison Coercion#

console.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.

Conclusion#

  • When a numeric value is concatenated with a string using the Addition operator, JavaScript coerces the number to a string.
  • When a string value is involved in a math operator (Non-Addition), JavaScript attempts to convert it to a numeric value.
  • When comparing values using the == or != operators, JavaScript performs the Abstract Equality Comparison Algorithm to make the values comparable.

References#

GET IN TOUCH

Let’s work together

I build exceptional and accessible digital experiences for the web

WRITE AN EMAIL