Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No colon after property name in object declaration, is it valid? [duplicate]

Tags:

javascript

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.

like image 784
Lacuno Avatar asked Dec 15 '16 14:12

Lacuno


People also ask

Can we have two properties with the same name inside an object?

You cannot. Property keys are unique. Follow TravisJ 's advice. You might want to look up the term 'multimap', too.

Can object property name be number?

According to the official JavaScript documentation you can define object literal property names using integers: Additionally, you can use a numeric or string literal for the name of a property.

How do you check if an object contains a property?

The hasOwnProperty() method will check if an object contains a direct property and will return true or false if it exists or not. The hasOwnProperty() method will only return true for direct properties and not inherited properties from the prototype chain.

What is the correct syntax for declaring an object literal?

Declaring methods and properties using Object Literal syntax The Object literal notation is basically an array of key:value pairs, with a colon separating the keys and values, and a comma after every key:value pair, except for the last, just like a regular array.


2 Answers

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
};
like image 72
nicovank Avatar answered Oct 21 '22 16:10

nicovank


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.

like image 26
Manoj Lodhi Avatar answered Oct 21 '22 14:10

Manoj Lodhi