call(back)

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 null

Hints

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.

ExpressionResultExpressionResult
1 + "0""10""0" == ""false
1 - "0"1null == 0false
1 + +"0"1null == undefinedtrue
"5" * "2"10[] == ![]true
1 + null1"10" > "9"false
1 + undefinedNaN10 > "9"true
true + true20.1 + 0.2 === 0.3false
[] + {}"[object Object]"NaN === NaNfalse
[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.

Asked at