26

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
  • 23,492
  • 9
  • 63
  • 110
Lacuno
  • 444
  • 4
  • 13

2 Answers2

39

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,157
  • 1
  • 21
  • 42
  • 1
    I'd name this a shorthand method (because when you call this property, its function gets the `this` context as `obj`, yet). –  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
5

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
  • 6,457
  • 2
  • 29
  • 39
Manoj Lodhi
  • 978
  • 4
  • 10