Defining methods
Learn to define methods inside an object and the shorthand syntax.
What is a method?
A function defined inside an object is called a method. Methods define the object's behavior and are accessed by key, like other properties.
const greeter = {
name: 'Alex',
greet: function() {
return 'Hello!';
}
};
greeter.greet(); // 'Hello!'To call it, you add parentheses after the property name. Without parentheses you only get the function itself, not its result.
Method shorthand
Since ES2015 you can write methods more concisely. Skip the function keyword and use the name and parentheses directly.
const greeter = {
name: 'Alex',
greet() {
return 'Hello!';
}
};This form is common in modern JavaScript and is equivalent to the function syntax. The shorthand behaves the same; you just type less.
Exercise Calculator object
Create an object named calc. Using the shorthand, define an add method that takes parameters a and b and returns their sum. Then print the result with console.log(calc.add(3, 5)).
Show example solution
const calc = {
add(a, b) {
return a + b;
}
};
console.log(calc.add(3, 5));
Test yourself
-
How do you call the method?
const greeter = { greet: function() { return 'Hello!'; } };- greeter.greet
- greet()
- greeter->greet()
- greeter.greet()
Show answer
greeter.greet() — Correct! You add parentheses to call the method.
-
Call the method
const greeter = { greet() { return 'Hello!'; } }; greeter.greet____;Show answer
const greeter = { greet() { return 'Hello!'; } }; greeter.greet(); -
Match each form
- greet: function() {}
- long form
- greet() {}
- shorthand
- greet()
- method call