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"