Method Shorthand Syntax
You'll learn: How to write object methods more cleanly by dropping the function keyword.
When you add methods to an object literal, JavaScript offers a cleaner, more concise syntax. Instead of writing methodName: function() { ... }, you can simply write methodName() { ... } — the function keyword is implied.
The Traditional Way
You already know how to define methods in objects:
const calculator = {
add: function(a, b) {
return a + b;
},
multiply: function(a, b) {
return a * b;
}
};
console.log(calculator.add(2, 3)); // 5
The Shorthand Way
Method shorthand syntax lets you skip the colon and function keyword:
const calculator = {
add(a, b) {
return a + b;
},
multiply(a, b) {
return a * b;
}
};
console.log(calculator.add(2, 3)); // 5
console.log(calculator.multiply(4, 5)); // 20
Both versions work identically — the shorthand is just easier to read and write. It's especially helpful when objects have many methods.
Mixing Styles
You can combine shorthand methods with regular properties:
const user = {
name: 'Alice',
age: 30,
greet() {
console.log(`Hi, I'm ${this.name}!`);
}
};
user.greet(); // "Hi, I'm Alice!"
Why It Matters
Think of it like abbreviations in everyday language — "cannot" vs "can't." Both communicate the same idea, but one is more concise. Method shorthand reduces visual clutter and makes your object definitions cleaner, especially in modern JavaScript where objects with multiple methods are common.
Key Takeaway: Method shorthand syntax (methodName() {}) is a cleaner alternative to methodName: function() {} when defining methods in object literals — they behave identically but shorthand is preferred in modern code.