DEV Community

Saloni Saraiya
Saloni Saraiya

Posted on • Originally published at Medium on

Methods vs Functions

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.

banner

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.

  1. Methods are associated with a specific class instance to call it.
  2. Methods cannot be accessed outside of a class, or they process other data.
  3. 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));
Enter fullscreen mode Exit fullscreen mode

2. Method

class Dog{
  bark(){
    console.log("dog has barked");
  }
}

let dog = new Dog();
dog.bark();
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)