Type coercion in JavaScript
Type coercion is the automatic conversion of a value from one data type to another. It happens during operations or comparisons that mix different data types.
Implicit vs Explicit Type Coercion
-
Implicit Type Coercion:
Happens automatically during operations.
Example:5 + '5' -
Explicit Type Coercion:
You convert manually with functions like
Number(),String(), and so on.
Example:Number('10')converts the string to a number.
Number to String Coercion
JavaScript coerces the number 99 into a string, then concatenates the two values into the string 1099.
String to Number Coercion
Here the string 10 is coerced into a number, giving 89.
Equality Comparison Coercion
Let's break it down.
-
[]is truthy, and!negates a truthy value, so![]evaluates tofalse. -
Now we have
[] == false.- Per the ECMAScript® Language Specification: if
Type(y)isBoolean, return the result of the comparisonToNumber(x) == y.
- Per the ECMAScript® Language Specification: if
-
So the expression becomes
[] == 0, since JavaScript coercesfalseto0.- Per the ECMAScript® Language Specification: if
Type(x)isObjectandType(y)is eitherStringorNumber, return the result of the comparisonToPrimitive(x) == y.
- Per the ECMAScript® Language Specification: if
-
[].toString()is'', which leaves us at'' == 0. JavaScript coerces''to0. -
Finally,
0 == 0istrue.
Whenever two values are compared with the == operator, JavaScript runs the Abstract Equality Comparison Algorithm.
Quick Recap
-
Type Coercion Types
- Implicit: Automatic conversion during operations
- Explicit: Manual conversion using functions
- Context-dependent behavior
- Operator-specific rules
-
Common Coercion Patterns
- String concatenation with numbers
- Mathematical operations with strings
- Boolean comparisons
- Object to primitive conversion
-
Best Practices
- Use strict equality (
===) when possible - Be explicit with type conversions
- Understand operator precedence
- Test edge cases thoroughly
- Use strict equality (