Method Shorthand Syntax
What you'll learn: How to define methods inside classes using the cleaner, modern syntax without the function keyword.
The Modern Way to Write Methods
When defining methods inside a class, JavaScript offers a shorthand syntax that lets you skip the function keyword entirely. Instead of writing out the full function syntax, you simply write the method name followed by parentheses and a function body.
This is the same convenient syntax you learned earlier for object literals (method shorthand in objects), now applied to classes.
The Old Way vs The New Way
Before method shorthand existed, you might have seen attempts to write:
class Dog {
constructor(name) {
this.name = name;
}
// This would be invalid!
bark: function() {
return `${this.name} says woof!`;
}
}
But classes don't work that way. Instead, you use shorthand syntax:
class Dog {
constructor(name) {
this.name = name;
}
// Clean shorthand syntax - just the method name
bark() {
return `${this.name} says woof!`;
}
fetch(item) {
return `${this.name} fetches the ${item}!`;
}
}
const buddy = new Dog('Buddy');
console.log(buddy.bark()); // "Buddy says woof!"
console.log(buddy.fetch('ball')); // "Buddy fetches the ball!"
No colons, no function keyword—just a clean method name followed by parameters and a body. This is the only way to define methods in classes (besides the special constructor method).
Why It Matters
The shorthand syntax makes your class definitions cleaner and more readable. It's not optional style—it's the standard way to write instance methods in classes.
Key Takeaway: In classes, define methods using shorthand syntax: just write the method name followed by () and the function body, with no function keyword needed.