0
{} + 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.

junlin
  • 1,835
  • 2
  • 25
  • 38

2 Answers2

2

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

abadalyan
  • 1,205
  • 8
  • 13
1

In the following snippet, both expressions are converted to strings, so you get the following results, which is expected:

[object Object]5
5[object Object]

The reason this is happening is because + can't be addition between numbers since {} can't be cast to a number. Instead + is considered string concatenation here and both operands get converted to strings.

console.log({} + 5 === '[object Object]5')
console.log(5 + {} === '5[object Object]')
jo_va
  • 13,504
  • 3
  • 23
  • 47