4 min read
•Question 14 of 50mediumWhat is Type Coercion in JavaScript?
Understanding implicit type conversion.
What You'll Learn
- Implicit vs explicit coercion
- Truthy and falsy values
- == vs === comparison
Type Coercion
JavaScript automatically converts values between types when needed.
Falsy Values
code.jsJavaScript
// All falsy values
false
0
-0
''
null
undefined
NaN
// Everything else is truthy
'0' // truthy
[] // truthy
{} // truthyImplicit Coercion
code.jsJavaScript
// String coercion
'5' + 3 // '53' (number to string)
'5' - 3 // 2 (string to number)
// Boolean coercion
!!'hello' // true
!!0 // false
// Comparison
'5' == 5 // true (coercion)
'5' === 5 // false (no coercion)== vs ===
| Operator | Type Coercion | Use Case |
|---|---|---|
| == | Yes | Almost never |
| === | No | Almost always |
code.jsJavaScript
null == undefined // true
null === undefined // false
[] == false // true
[] === false // false
'' == false // true
'' === false // falseExplicit Coercion
code.jsJavaScript
Number('5') // 5
String(5) // '5'
Boolean(1) // true
parseInt('10px') // 10