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.
You cannot. Property keys are unique. Follow TravisJ 's advice. You might want to look up the term 'multimap', too.
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.
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.
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.
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
};
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With