Search code examples
javascriptimplicit-conversion

JS object and number addition


{} + 5 === 5
5 + {} === '5[object Object]'

How is the first expression {} + 5 === 5 calculated?

The second expression 5 + {} === '5[object Object]' is expected result.

===== Edit ====

({}) + 5 === '[object Object]5'

Which might be to say: {} in first expression was ignored as the question comment says.


Solution

  • The {} at the beginning of a line is considered a code block rather than an object literal. Thus {} + 5 is not considered a binary addition between two values and evaluates to +5, unary + operator applied to 5.

    When {} is placed inside round brackets it turns into object literal and the entire expression evaluates to '[object Object]5'

    More details on this gotcha can be found here