27

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.

2
  • 6
    ES6 short object notation Commented Dec 15, 2016 at 14:07
  • 1
    x is an object with a function named a with an argument named b Commented Dec 15, 2016 at 14:08

2 Answers 2

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

6 Comments

I'd name this a shorthand method (because when you call this property, its function gets the this context as obj, yet).
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!
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.
@GOTO0 That is very accurate indeed.
@ArturoTorresSánchez see my question about it
|
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.

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.