Functions vs. Methods
Let's break down the difference between a function and a method in simple terms, using everyday analogies.
Function:
A function is like a standalone recipe. Imagine you have a recipe for making a sandwich. It's a set of instructions that you can follow to make a sandwich. You can use this recipe to make many sandwiches, whenever you want.
Method:
A method, on the other hand, is like a special step in a particular recipe. Let's say your sandwich recipe (a class) has a step called 'spread butter'. This step is unique to the sandwich recipe and tells you how to spread butter on the bread. It's part of the overall sandwich-making process.
So, in simple terms, a method is a special set of instructions (like a step in a recipe) that belongs to a specific recipe (class), while a function is a standalone recipe that you can use to make something (perform a task) whenever you want.
Here's a code analogy in JavaScript:
Function:
function makeSandwich() { // Instructions to make a sandwich console.log('Spread butter'); console.log('Add cheese'); console.log('Put the slices together'); } makeSandwich(); // Making a sandwich using the function
Method:
const sandwichRecipe = { spreadButter: function() { console.log('Spread butter'); // This is a method to spread butter }, addCheese: function() { console.log('Add cheese'); // This is another method to add cheese }, assemble: function() { console.log('Put the slices together'); // This is another method to assemble the sandwich } }; sandwichRecipe.spreadButter(); // Using a method to spread butter in the sandwich recipe
In summary, functions are like standalone recipes, and methods are specific steps (or actions) within a particular recipe (or class) that help you complete a task or make something.
Subscribe to my newsletter
Read articles from Abere Oghenefejiro directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Abere Oghenefejiro
Abere Oghenefejiro
I am a recent graduate of the University of Benin. I am currently learning frontend development and actively looking for developer roles.