Paul A Jungwirth Paul A Jungwirth - 1 year ago 82
Node.js Question

Javascript key/value pair with no braces

I noticed that in both nodejs and a browser, you can give a key/value pair with no braces, and it is accepted. It evaluates to the value half of the pair. For instance:

> { id: 5 }
{ id: 5 }
> id: 5

But if you quote
, then node wants more input:

> "id": 5

So what is going on here? What syntax is
id: 5
when it has no braces?

Answer Source

This is not a bug. You are declaring a label, followed by a Number literal.

The console defaults to printing out the result of the last expression in your code.

Hence it prints 5.

Your confusion stems from the fact that the exact same syntax can mean totally different things, depending on the context.

This is for the JavaScript parser to decide according to the rules of the spec.

Another example would be:


Is that an object literal or a block? The context provides the answer.

From the spec:

A Statement may be prefixed by a label. Labelled statements are only used in conjunction with labelled break and continue statements. ECMAScript has no goto statement. A Statement can be part of a LabelledStatement, which itself can be part of a LabelledStatement, and so on. The labels introduced this way are collectively referred to as the “current label set” when describing the semantics of individual statements.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download