Skip to main content
0 reactions

How to Call a Method on an Object in JavaScript

A card titled Call a Method, labelled JavaScript Basics, showing cafe.greet(“Sam”) printing Welcome, Sam! and cafe.greet without brackets printing [Function: greet].
Call a Method: Run a function that belongs to an object.

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

SyntaxJavaScript
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

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

cafe.jsJavaScript
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

TerminalBash
node cafe.js
OutputPlain text
Welcome, Sam!

The method ran with "Sam" as customer, and console.log printed what it gave back.

Common Mistakes

MistakeWhat happensDo this instead
Leaving out the brackets: cafe.greetYou get the function itself, printed as [Function: greet], and it doesn’t runAdd the brackets: cafe.greet("Sam")
Calling a method the object doesn’t haveTypeError: cafe.order is not a functionCheck 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

JavaScript is a trademark of Oracle Corporation in the United States. Node.js is a trademark of the OpenJS Foundation.

0 comments