Why this happened
{}+{} output- NaN
({} + {})output- ''[object Object][object Object]''
Why show that kind of result?
Why this happened
{}+{} output- NaN
({} + {})output- ''[object Object][object Object]''
Why show that kind of result?
When you write {}
in some ways, if what the "duplicate" answer says is correct, it might be interpreted as a code block instead of an empty object. The empty block has no return statement, so it returns undefined
.
undefined + undefined
returns NaN because it tries to do a mathematical addition between two values that are not numbers. When you write {} + {}
but don't do anything with the result, Chrome again evaluates the +
as the addition and both {}
as undefined.
However, as soon as you actually do something with the result, the behavior is different because the browser understands that you're using the implicit object declaration syntax. If you do say, var x = {} + {}
, Chrome creates two objects and tries to convert them into a value that can be used with the +
operator. So it converts the objects into string representations and concatenates the strings together.
The same thing happens when you use parentheses, because blocks can't exist inside parenthesis like that, so it can't mistake the {}
for an empty block.
PS: I had it wrong at first and I'm just taking what I read on that other answer now.