Difference between Functions and Methods in Javascript
Before discussing the difference between a function and a method, we must understand, what is a function and what is a method. So, let’s understand a function first.
Function in Javascript
- A function in JavaScript is a block of code, which is designed to perform a particular task.
- It is a standalone piece of code that can be called from anywhere in the program.
- We need to use function keyword, in order to define a function.
function greet() {
console.log("Hello, world!");
}
greet(); // Calls the function
So, we can say that
- functions can be declared independently.
- functions can be called without being associated with an object.
- functions are not tied to any object.
Now, Let’s see, what is a method
Methods in Javascript
- A method is also a function, but it is always associated with either an object or with a class.
- We have to write a method always inside an object or inside a class.
- When we write a method inside an object, then we need to use function keyword while defining it.
- When we write a method inside a class, then we can’t use function keyword while defining it.
- So, a method is a funnction which is a property of an object or a class.
Definition – When a function is defined as a property of an object or a class, it is called a method of that object or the class.
Methods associated to an object
const person = {
name: "Rajesh",
greet: function() {
console.log("Hello, my name is " + this.name + "!");
}
};
person.greet(); // Calls the method
Methods associated to a class
class person {
name;
greet() {
console.log(`Hello, my name is ${this.name}`);
}
}
let obj = new person();
obj.name = "Rajesh";
obj.greet();
Difference between function and method
function | method (object) | method (class) |
We need to use function keyword while defining a function | We need to use function keyword while defining a method associated to an object | function keyword should not be used when we define a method associated to a class |
We can call function without using any object reference | We have to use object reference for calling method | We have to use object reference for calling method |
Functions are general-purpose blocks of code that can be used independently | methods are specific functions associated with an object | methods are specific functions associated with a class |
In a standalone function, this can have different values depending on how the function is invoked. | In a method, this refers to the object to which the method belongs, allowing methods to access and modify the object’s properties | In a method, this refers to the object to which the method belongs, allowing methods to access and modify the object’s properties |