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. So you end up with
Object]""[object Object][object, the result of concatenating them.
Object]"
No comments:
Post a Comment