A method is a function stored in an object. To call it, write the object, a dot, the method’s name and round brackets with any arguments: cafe.greet("Sam").
Every command and output on this page is real, run with Node.js 26.13.1 on macOS.
Syntax
object.method(arguments)
object: the object that has the method..method: a dot and the method’s name.(arguments): round brackets with the values to pass in, separated by commas. Write empty brackets when there are none.
See Method definitions (opens in a new tab) on MDN.
Prerequisites
- Node.js, to run the example. Install it from the Node.js download page (opens in a new tab).
The Example
A café object with a name and a greet method that welcomes a customer. The file is cafe.js.
Step 1: Write the Code
const cafe = {
name: "Corner Cafe",
greet(customer) {
return "Welcome, " + customer + "!";
},
};
console.log(cafe.greet("Sam"));
greet(customer) { … } inside the object defines the method. The last line calls it with "Sam".
Step 2: Run It
node cafe.js
Welcome, Sam!
The method ran with "Sam" as customer, and console.log printed what it gave back.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Leaving out the brackets: cafe.greet | You get the function itself, printed as [Function: greet], and it doesn’t run | Add the brackets: cafe.greet("Sam") |
| Calling a method the object doesn’t have | TypeError: cafe.order is not a function | Check the method’s name and its capital letters |
FAQ
Do strings and arrays have methods too?
Yes. Built-in values come with methods, so "sam".toUpperCase() gives SAM.
Conclusion
Call a method with object.method(arguments). Without the brackets you only get the function, not its result.
Additional Resources
- Method definitions (opens in a new tab) (MDN)
- Working with objects (opens in a new tab) (MDN)
- Run Node.js scripts from the command line (opens in a new tab) (Node.js docs)
JavaScript is a trademark of Oracle Corporation in the United States. Node.js is a trademark of the OpenJS Foundation.
0 comments