JavaScript Type Coercion

javascript type coercion

Type coercion is the process of converting value from one type to another when doing implicitly.

Since javascript is loosely type language, any primitive or object can be implicitly converted to following types easily, when work with different operators. This behavior makes more misconceptions.

String
Number
Boolean

Different Type of Coercion

Any Type ⟾ String

  • 5 + '' // "5", Number is converted to string.
    1 + 2 + "3" // "33", Since statement evaluate from left to right, 1 + 2 = 3 and concatenate with “3”.
    However, "1" + 2 + 3 //"123".
  • Have you thought about Array or Object work with string?
    Array and Object trigger toString() when Coercion to string.

[1] + '' //"1"
[1,2] + [3,4] //"1,23,4"

In Object, when calling toString() It will give "[object Object]" as a output.
Object.assign({}) + '' // "[object Object]"

But {} + '' //0 why 0 in here, because before creating the object, + operator Coerce empty string to number . Basically, It would like this +'' // 0

Any Type ⟾ Number

  • 4 > '3' what would be the output? true that because string 3 coercion to number.
  • 4 / "2" // 2 string coerces to number.
  • +, - and ~ unary operators are used to convert string to number
    +"2" //2
    -"2" //-2
    ~ unary operator comes in handy, so that if we use twice same operator we can get same converted number.
    ~~"1" //1
  • Other than, type convert to NaN. which mean It’s not a number .
    This is the only type which not equal to itself.
    NaN == NaN //false
  • Array and Object trigger valueOf() when Coercion to number.
    +[] //0
    +[2] //2
    +[2,3] //NaN

Any Type ⟾ Boolean

In JavaScript, true and false are defined for representing values of Boolean. But some cases 0, 1 or null, [] or '' make lots of misconceptions around the code.

  • We know that 0 and 1 are just number representation in every programming language. But in JavaScript, these two values are special because 0 coericion as false and 1 coercion as true.
  • Logical operators such as || and && do boolean conversions internally, but return the value of original operands even though if they are not boolean.
    1 || false // 1
    true && [] //[]
  • List of falsy values.
    '' //false
    false //false
    0 //false
    -0 //false
    NaN //false
    null //false
    undefined //false

    Any value that is not in above list is converted to true.
  • Object and Array in If condition is consider as true
    if([]) // this will evaluate as true
    if({}) //same as this

Summaries

Process of implicitly converting value from one type to another we call it Coercion in JavaScript. Basically any javascript type can be coercion to String, Number or Boolean. This behavior makes more misconceptions around the code.

Leave a Reply