Methods vs Functions
Saloni Saraiya
Posted on December 22, 2022
Let's clear some fundamentals.
Hi, devs,
You might be calling any function as a method or a function randomly in your day-to-day software development lifecycle.
So, Let's understand the primary difference between Methods and Functions.
What is a function?
A function is a set of instructions separated from the main code, to call it repetitively wherever needed.
A function can take arguments as inputs to process specific tasks.
A function can have a return value with a specific type to generate output for a particular task.
Functions are part of functional and procedural programming concepts.
What is a method?
A method is also a set of instructions separated from the main code, to call it repetitively wherever needed.
A method can also take arguments.
A method can also have a return value and type.
BUTโฆ.
Here are the key differences between a function and a method.
- Methods are associated with a specific class instance to call it.
- Methods cannot be accessed outside of a class, or they process other data.
- Methods are part of Object-oriented programming concepts.
Basically,
If a function is associated with a class, it's a method. Otherwise, it is simply a function.
Letโs see an example
1. Function
function sum(a,b,c){
return a+b+c;
}
console.log(sum(1,2,3));
2. Method
class Dog{
bark(){
console.log("dog has barked");
}
}
let dog = new Dog();
dog.bark();
and with that,
Thatโs it for this article. I hope I have made you clear.
Let me know in the comments about small but mostly ignored topics you want me to discuss.
Bye. ๐๐ผ
Keep Coding ๐ฉ๐ปโ๐ป, keep learning ๐ฏ
About me๐ฉ๐ปโ๐ป
I am a Backend Developer at DhiWise.
You can also follow me on LinkedIn and Twitter for more tech updates.
Posted on December 22, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.