Methods vs Function Properties
You'll learn: How method shorthand differs from traditional function properties, and why both exist in JavaScript objects.
The Two Ways to Write Methods
In JavaScript, you can add functions to objects in two ways that look different but behave almost identically:
// Traditional function property
const calculator = {
add: function(a, b) {
return a + b;
}
};
// Method shorthand (ES6+)
const calculator2 = {
add(a, b) {
return a + b;
}
};
Both create a method called add that does exactly the same thing. You call them identically:
calculator.add(2, 3); // 5
calculator2.add(2, 3); // 5
What's the Real Difference?
The shorthand is simply syntactic sugar—a cleaner way to write the same thing. Think of it like saying "I'll go" versus "I will go"—different forms, same meaning.
When It Matters
There's one subtle technical difference: method shorthand creates a true "method" with a special internal property ([[HomeObject]]), which becomes important for advanced features you'll learn later. But for now, treat them as functionally identical.
Why Use Shorthand?
- Less typing – no
functionkeyword needed - Cleaner readability – easier to scan object definitions
- Modern convention – the standard in current JavaScript
const user = {
name: 'Alice',
greet: function() { // Old way - verbose
return 'Hello!';
},
farewell() { // New way - concise
return 'Goodbye!';
}
};
Key Takeaway: Method shorthand (methodName() {}) and function properties (methodName: function() {}) are interchangeable for basic usage—shorthand is just cleaner, modern syntax for the same thing.