Predict the Result: Type Coercion
What happens when you add "0" to a number? Evaluate each expression:
1 + "0" 1 - "0" 1 + +"0" "5" * "2"
1 + null 1 + undefined true + true [] + {}
[1, 2, 3] + [4] 0 == "" "0" == "" null == 0
null == undefined [] == ![] "10" > "9" 10 > "9"
0.1 + 0.2 === 0.3 NaN === NaN typeof nullHints
Hint 1
+ concatenates as soon as either side becomes a string; every other arithmetic operator converts to numbers.
Hint 2
Under ==, null equals only undefined, and objects are converted to primitives before comparing.
Solution
Show the approach
Answer
The rule behind all of them: + concatenates if either side becomes a string, and every other arithmetic operator converts to numbers.
| Expression | Result | Expression | Result |
|---|---|---|---|
1 + "0" | "10" | "0" == "" | false |
1 - "0" | 1 | null == 0 | false |
1 + +"0" | 1 | null == undefined | true |
"5" * "2" | 10 | [] == ![] | true |
1 + null | 1 | "10" > "9" | false |
1 + undefined | NaN | 10 > "9" | true |
true + true | 2 | 0.1 + 0.2 === 0.3 | false |
[] + {} | "[object Object]" | NaN === NaN | false |
[1, 2, 3] + [4] | "1,2,34" | typeof null | "object" |
0 == "" | true |
Two strings compare character by character, so "10" > "9" is false. null equals only undefined under ==. [] == ![] is true because ![] is false, and both sides then become 0.