What is the difference between a function and a method in JavaScript?
Functions and methods are very similar but differ in a few distinct ways.
The main difference between a function and a method
- A function is defined outside of an object
- A method is defined as the property of an object
In addition, methods are implicitly given a reference to the parent object (this) and are able to operate on other data that is stored within the object.
When to use a function or a method
Methods are recommended when you're creating a function that should belong with a collection of other functions and data. The eat and isHappy methods for Eliza the Bird are good examples. The object acts as a way to keep the related functions and data together.
A function is recommended if you are creating generic code that may be useful in many different contexts. For example, a function like removeArrayItem(array, item); might be useful in many situations and so wouldn't need to be attached to a specific object.