catalins.tech with Gatsby

What Is The Difference Between A Method and A Function? πŸ€”

2020 Jul 2nd

In a similar fashion to “What Is The Difference Between Parameter And Argument? πŸ€”“, most of the times we use the words “method” and “function” interchangeably. Even though they are almost the same, there is a subtle difference between them.

WHAT IS THE DIFFERENCE THEN

When we want to write reusable code, we wrap that piece of code in a function. The function is independent of any object, has its own scope, and it allows us to call it from anywhere within the program. 

function addNumbers(num1, num2) {
    return num1+num2;
}

The snippet above illustrates a function. The function carries out a specific task, which is to add two numbers. You pass two numbers, and it returns the result of adding them together. We can call this function from anywhere in the program – addNumbers(2, 3).

METHOD

On the other hand, a method is associated with an object. That means we have to call the method on an object. In other words, the method operates on the object’s data.

As an example, if we have an object called Mathsand a method addNumbersinside the object, we cannot call the method by its name. We have to create an instance of the object and call that method on the object. For instance, we call it something like that – mathObj.addNumbers(num1,num2).

CONCLUSION

I hope you find this article useful and I hope it is clear now what are the differences between a method and a function.

Remember that a function is a reusable piece of code we can call from anywhere within the program. On the other hand, we call methods on an object, and it operates on the object’s data.

OTHER ARTICLES OF MINE