Object Method Definition Shorthand
April 1, 2021
Object methods in ES5 require the function
statement.
// ES5
var operations = {
sum: function (x, y) {
return x + y;
},
multiply: function (x, y) {
return x * y;
},
divide: function (x, y) {
return x / y;
},
};
console.log(operations.sum(1, 2)); // 3
console.log(operations.multiply(2, 5)); // 10
console.log(operations.divide(4, 4)); // 1
This is no longer necessary in ES6, you can use the following shorthand syntax:
const operations = {
sum(x, y) {
return x + y;
},
multiply(x, y) {
return x * y;
},
divide(x, y) {
return x / y;
},
};
console.log(operations.sum(1, 2)); // 3
console.log(operations.multiply(2, 5)); // 10
console.log(operations.divide(4, 4)); // 1