Chris Middleton
Chris Middleton

Reputation: 5952

Why isn't using property definition syntax outside of an object a syntax error?

I saw this code on David Shariff's JavaScript quiz and was surprised it wasn't a syntax error:

var bar = 1,
    foo = {};

foo: {
    bar: 2;
    baz: ++bar;
};
foo.baz + foo.bar + bar;

How can you use the name: value syntax outside of any object like that?

Upvotes: 1

Views: 39

Answers (2)

BoltClock
BoltClock

Reputation: 724542

The foo: in this case is a label. It's not very useful in this context since there aren't any nearby loops, but it's valid syntax.

Note that the foo: label is not linked to the foo variable in any way. The structure that directly follows the label is simply a block containing, strangely enough, two more labels: bar: and baz: which are followed by two equally plain statements.

As a result, the foo object remains empty, and your last line does not work the way you would expect it to. The result of the last line, and therefore the answer to the quiz question, is

NaN

Upvotes: 1

Amadan
Amadan

Reputation: 198556

This is not name: value; this is label: statement. See more at MDN. This code is equivalent to:

var bar = 1,
    foo = {};

{
  2;
  ++bar;
};

foo.baz + foo.bar + bar;

Upvotes: 2

Related Questions