On the other hand, methods are functions bound to an object. Let’s go over each one by one.
Functions in JavaScript
As mentioned above, a function is nothing but a block of code enclosed inside curly brackets and used to fulfill a specific role or perform a particular task. Working with a function generally consists of two parts, the first is the function definition, and the second is the function call.
In the function definition, a function is created with the function keyword, given a name and a block of code to perform a task like:
// Block of code goes here
}
This above code snippet is to create a function which is named as greetUser(). The second part of working with function is the function call. The function call is essentially the line where we call the function using its name to perform the task written inside it:
This function call does not require any special keyword. An example of the function would be:
console.log("Hello and Welcome to LinuxHint!");
}
greetUser();
Upon execution of this code snippet, you’ll get the following output onto the terminal:
The greeting was printed onto the terminal
Methods in JavaScript
Methods are functions, they are written to uptake a specific purpose, and they also have two parts which include the function definition and the function call (called method definition and method call). However, methods are defined inside an Object, which differentiates them from normal functions. Take the following lines to showcase the method definition:
greetUser: function () {
console.log("Hello and Welcome to LinuxHint!");
},
};
In this code snippet, there is an object named as siteBot which contains an attribute greetUser which is set to a function() with some tasks inside it. Now, this greetUser is called a method of the siteBot object.
To call a method, the call must use a dot operator with their object’s name, and then at the end, you place the parenthesis like
The complete code snippet is as:
greetUser: function () {
console.log("Hello and Welcome to LinuxHint!");
},
};
siteBot.greetUser();
Upon executing the code snippet mentioned above, the following output is displayed on the terminal:
As you can see, siteBot object printed the greetings on the terminal. Now, try to call this greetUser() method like you would call a normal function using the dot operator or the object’s name:
You will get the following output in the terminal:
From this output, it is clear that you cannot call methods like you would call a normal function.
Conclusion
Functions and methods are quite different in their working because functions are not bound by any object, whereas methods are bound by the object in which they are defined. Methods are essentially functions bounded to a specific object. Function calls require no special keyword or operator, whereas method calls require the object’s name and the dot operator. Both of them are written to perform a particular purpose.