JavaScript Puzzles
(introduction)
Null and Numbers
Given these results:
> null == 0
false
> null === 0
false
> null > 0
false
Why does null >= 0
give true
(even though >= is mathematically equivalent to "greater OR
equal")?
Solution and explanation:
When using an equality operator (e.g. "==" or "!=="), JavaScript compares by looking at the types and seeing if they are the same (and in the case of "==", it tries a couple of other conversions).
However, comparison operators (e.g. ">") only make sense for numbers, so it always tries to convert both operands to a number first:
null > 0 => Number(null) > Number(0) => 0 > 0 => false
null >= 0 => Number(null) >= Number(0) => 0 >= 0 => true
Adding Lists and Objects
The following can be typed in a JavaScript console:
> {} + {}
NaN
> {} + []
0
> [] + {}
'[object Object]'
> [] + []
''
However, if you assign the first two values to a variable, the results change:
> const x = {} + [];
> x
'[object Object]'