Monday 27 November 2017

javascript - why ({}+{})="[object Object][object Object]"?





I have tested the
code:




{}+{} =
NaN;
({}+{}) = "[object Object][object
Object]";


Why does
adding the () change the result?



Answer




{}+{} is a
block followed by an expression. The first
{} is the block (like the kind you attach to an
if statement), the +{} is the
expression. The first {} is a block because when the parser is
looking for a statement and sees {, it interprets it as the
opening of a block. That block, being empty, does nothing. Having processed the block,
the parser sees the + and reads it as a unary
+. That shifts the parser into handling an expression. In an
expression, a { starts an object initializer instead of a
block, so the {} is an object initializer. The object
initializer creates an object, which + then tries to coerce to
a number, getting
NaN.



In
({}+{}), the opening ( shifts the
parser into the mode where it's expecting an expression, not a statement. So the
() contains two object initializers with a
binary + (e.g., the "addition" operator,
which can be arithmetic or string concatenation) between them. The binary
+ operator will attempt to add or concatenate depending on its
operands. It coerces its operands to primitives, and in the case of
{}, they each become the string "[object
Object]"
. So you end up with "[object Object][object
Object]"
, the result of concatenating them.



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...