The Difference Between a Method and a Function

Communication is crucial in software, and knowing the nuanced differences between certain things can help you be more descriptive when you are describing a problem or solution.

One common thing I hear people mix up is a "method" and a "function".

In JavaScript, the terms "function" and "method" are often used interchangeably, but there is a difference between the two.

A "function" is a standalone block of code that can be called by its name and can optionally take arguments and return a value. It is not associated with any object or class.

A "method" is a function that is associated with an object or class.

It is called on an instance of the object or the class and can access the properties and methods of that object or class.

Example

Let's look at a simple example of both so that it's hopefully clear.

In the following, we will generate a user's full name with a function and a method.

// function
function fullName(firstName, secondName) {
  return `${firstName} ${secondName}`
}

// object with method
const user = {
  firstName: "Niall",
  secondName: "Maher",
  // method
  fullName: function() {
    return `${this.firstName} ${this.secondName}`
  }
}

And then to use the function and method:

// Calling the function
console.log(fullName("Niall", "Maher")); // logs "Niall Maher"
// Calling the method
console.log(user.fullName()); // logs "Niall Maher"
BeginnerJavaScriptFundamentals
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.