ES6 Everyday: Shorthand Properties and Methods
Take a look at this:
var name = "Logan";
var age = 27;
var person = {
name: name,
age: age
};
console.log(person.name); // Logan
Something about name: name
and age: age
seems so silly and redundant, right?
ES6 agrees and provides us with a shorthand property syntax:
var name = "Logan";
var age = 27;
var person = {
name,
age
};
console.log(person.name); // Logan
Here we are just plopping a reference to our name
variable directly in the object literal, which ES6 expands for us into a property.
Similarly, didn’t the syntax for specifying a function in an object literal always seem a little verbose to you?
var person = {
greet: function() {
console.log('Hello!');
}
};
person.greet(); // Hello!
Well, ES6 provides us with a shorthand method syntax too:
var person = {
greet() {
console.log('Hello!');
}
};
person.greet(); // Hello!
Hey! Take this for a spin yourself in an ES6 Fiddle and enjoy your weekend!