JavaScript’s type coercion and dynamic typing system are full of subtle (and sometimes surprising) behaviors.
Understanding these quirks can make you much more confident and effective as a JS developer.
Here’s a list of not-so-obvious JavaScript type coercion examples, grouped into categories with explanations:
1. String vs Number Comparison
Expression |
Value |
Reason |
'10' < '2' |
true |
Lexicographic comparison: '1' comes before '2' |
'10' < 2 |
false |
string '10' is coerced to number 10 |
'5' == 5 |
true |
string '5' is coerced to number 5 |
'5' === 5 |
false |
strict equality, no type coercion |
Rule: Loose equality (==) allows type coercion. Strict equality (===) does not.
2. Falsy Values
JavaScript has falsy values that act like false in boolean contexts:
Expression |
Value |
Boolean(' ') |
false |
Boolean(0) |
false |
Boolean(null) |
false |
Boolean(undefined) |
false |
Boolean(NaN) |
false |
Boolean([]) |
true |
Boolean({}) |
true |
Note: [] and {} are truthy, even though they're empty.
3. Array and Object Coercion
Expression |
Value |
Reason |
[] + [] |
' ' |
both arrays are coerced to strings → ' ' + ' ' |
[] + {} |
'[object Object]' |
[] → ' ', {} → '[object Object]' ' ' + '[object Object]' → '[object Object]' |
[] == false |
true |
[] → ' ' → ' ' == false → true |
[0] == false |
true |
[0] → '0' → 0 == false → true |
[1,2] + [3,4] |
'1,23,4' |
arrays are stringified → '1,2' + '3,4' |
4. Arithmetic with Non-numbers
Expression |
Value |
Reason |
'5' - 2 |
3 |
'5' is coerced to number |
'5' + 2 |
'52' |
'+' triggers string concatenation |
null + 1 |
1 |
null → 0 |
undefined + 1 |
NaN |
undefined → NaN |
true + 1 |
2 |
true → 1 |
false + 1 |
1 |
false → 0 |
"abc" * 33 |
NaN |
Cannot coerce "abc" to Number → NaN |
33 / 0 |
Infinity |
Division by zero → Infinity |
0 / 0 |
NaN |
Undefined division → NaN |
Note: The +
operator behaves differently depending on whether one side is a string — it prefers string concatenation over numeric addition.
5. Equality Weirdness
Expression |
Value |
Reason |
null == undefined |
true |
only loosely equal to each other |
null === undefined |
false |
different types |
[] == ' ' |
true |
[] → ' ' |
[null] == ' ' |
true |
[null] → ' ' |
[undefined] == ' ' |
true |
[undefined] → ' ' |
{} == {} OR [] == [] |
false |
different references |
NaN == NaN |
false |
NaN is not equal to anything, even itself |
6. typeof
Quirks
Expression |
Value |
Reason |
typeof null |
'object' |
Legacy bug in JavaScript |
typeof NaN |
'number' |
NaN is actually a special kind of number
|
typeof [] , typeof {} |
'object' |
Arrays are objects too |
typeof function(){} |
'function' |
Functions are a special kind of object |
Best Practices
- Always use
===
instead of ==
unless you're very sure about coercion.
- Use
Number()
, Boolean()
, or String()
explicitly when converting types.
- For checking arrays:
Array.isArray(value)
- For checking NaN:
Number.isNaN(value)
or Object.is(value, NaN)
Top comments (0)