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#
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#
Here, the string 10
is coerced into a numeric value, resulting in a number of 89
.
Equality Comparison Coercion#
let's take a minute to break it down
-
[]
is a truthy value applying!
to a truthy value negates it, so![]
evaluates tofalse
. -
Now, we have
[] == false
- According to ECMAScript® Language Specification - If
Type(y)
isBoolean
, return the result of the comparisonToNumber(x) == y
.
- According to ECMAScript® Language Specification - If
-
So, the expression becomes
[] == 0
in this case JavaScript coercesfalse
to0
.- According to ECMAScript® Language Specification - If
Type(x)
isObject
andType(y)
is eitherString
orNumber
, return the result of the comparisonToPrimitive(x) == y
.
- According to ECMAScript® Language Specification - If
-
Therefore,
[].toString()
is''
which leave us at'' == 0
JavaScript coerces''
to0
-
Finall,
0 == 0
istrue
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.