2
var obj = {
    foo: function() { return "this is foo"; },
    bar() { return "this is bar"; }
}

Executing this in NodeJS leads yields a SyntaxError at bar^( on line 3 - as would be expected.

Chrome and Firefox seem to be perfectly happy though, with what seems to be obviously wrong:

console.log(obj.foo()); // "this is foo"
console.log(obj.bar()); // "this is bar" 

Why do browser engines support this syntax? Is there documentation on this behaviour?

cjoy
  • 406
  • 5
  • 14

1 Answers1

1

As pointed out by jcubic, ES6 syntax is the answer. Specifically, the Object Literal Extensions.

Here is a snippet from Kyle Simpson's great YDKJS series.

Object Literal Extensions (source)

ES6 adds a number of important convenience extensions to the humble { .. } object literal.

Concise Properties

You're certainly familiar with declaring object literals in this form:

var x = 2, y = 3,
    o = {
        x: x,
        y: y
    };

If it's always felt redundant to say x: x all over, there's good news. If you need to define a property that is the same name as a lexical identifier, you can shorten it from x: x to x. Consider:

var x = 2, y = 3,
    o = {
        x,
        y
    };

Concise Methods (source)

In a similar spirit to concise properties we just examined, functions attached to properties in object literals also have a concise form, for convenience.

The old way:

var o = {
    x: function(){
        // ..
    },
    y: function(){
        // ..
    }
}

And as of ES6:

var o = {
    x() {
        // ..
    },
    y() {
        // ..
    }
}
cjoy
  • 406
  • 5
  • 14