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); // 1099JavaScript 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); // 89Here, the string 10 is coerced into a numeric value, resulting in a number of 89.
Equality Comparison Coercion#
console.log([] == ![]); // truelet'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
[] == 0in this case JavaScript coercesfalseto0.- According to ECMAScript® Language Specification - If
Type(x)isObjectandType(y)is eitherStringorNumber, return the result of the comparisonToPrimitive(x) == y.
- According to ECMAScript® Language Specification - If
-
Therefore,
[].toString()is''which leave us at'' == 0JavaScript coerces''to0 -
Finall,
0 == 0istrue
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.