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?

2
  • 1
    It's new ES6 syntax for object literals, try adding --harmony to node and it will work too. Commented Feb 26, 2016 at 10:44
  • thank you, makes perfect sense now - time to read up on ES6 :) Commented Feb 26, 2016 at 11:18

1 Answer 1

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() {
        // ..
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.