25

I entered this expression in the Firefox and Chrome Dev Console and I wonder why it is valid JavaScript:

var x = { a (b) {} };
console.log(x);

x is then set to an object with the property "a" containing a function called "a" with an argument identifier "b". How is this valid JavaScript syntax? The colon is missing after "a" and I do not understand the function definition.

ThisSuitIsBlackNot
  • 22,821
  • 9
  • 57
  • 105
Lacuno
  • 424
  • 4
  • 13

2 Answers2

40

This is ES6 / ES2015 syntactic sugar (Property shorthand). With ES6:

const obj = {
    a(b) { 
        // Shorthand method
        // `this` context is `obj`
    },
    c
};

is equal to

var obj = {
    a: function a(b) {

    },
    c: c
};
nicovank
  • 3,080
  • 1
  • 20
  • 40
  • 1
    I'd name this a shorthand method (because when you call this property, its function gets the `this` context as `obj`, yet). – Klaider Dec 15 '16 at 14:17
  • 1
    Is the OP case yes, but in general you can not use semicolons for any property, so I rather not rename it (I will add a comment though). Thank you for the edit btw! – nicovank Dec 15 '16 at 14:19
  • Note that there is a subtle difference. In your first snippet, `obj.a` is not a constructor. In the second snippet, `new obj.a` works as usual. – GOTO 0 Dec 15 '16 at 15:42
  • @GOTO0 That is very accurate indeed. – nicovank Dec 15 '16 at 15:53
  • @GOTO0, why is that? – Arturo Torres Sánchez Dec 15 '16 at 19:49
  • 1
    @ArturoTorresSánchez see [my question about it](http://stackoverflow.com/questions/41193117/constructor-behaving-differently-using-es6-shorthand-notation) – nicovank Jan 09 '17 at 16:47
6

In JavaScript, when you write:

var x = { a (b) {} };

It will consider it as:

var x = { 
    a: function (b) {

     }
   }

For example, you can check this and it will clear your doubt:

var x = { a (b) { console.info('function called') } };
x.a(); 

This will call the function which is assigned to property a of object x.

trashr0x
  • 5,979
  • 2
  • 27
  • 38
Manoj Lodhi
  • 978
  • 4
  • 10