In this tutorial we will see actual difference between a method and a function with examples.
A function is a set of statements for the purpose of code reusability. And it performs a task and can be called anywhere in your program. A function is a basic block for writing modular codes.
In general: a method belongs to a class and is similar to a function.
But in JavaScript, method is a function that belongs to an object. As everything in JavaScript is an object; including function, and an array.
Example for function
const power = function (base, exponent) {
let result = 1;
for (let count = 0; count < exponent; count++) {
result *= base;
}
return result;
};
console.log(power(2, 4));
// Output → 16
Another example for function
const factorial = function (n) {
return n > 2 ? n * factorial(n - 1) : 1;
};
console.log(factorial(5));
// Output → 120
Example for method
const celebrity = {
firstName: "Aishwarya",
lastName: "Rai",
profession: "Actress",
getFullName: function () {
return this.firstName + " " + this.lastName;
},
};
console.log(celebrity.getFullName());
// Output → Aishwarya Rai
Here method named getFullName is accessed via object i.e celebrity.getFullName().
Hope you learn something new. If this article was helpful, share with other.
Happy coding
Related Articles
Deepen your understanding with these curated continuations.
Convert array to an object in JavaScript
This article explains simplest and quickest way to convert array to an object in JavaScript. Using widely accepted spread operator `...` makes easy to do it.
How to Update an Array Element in JavaScript
Learn the simplest ways to update array elements in JavaScript. This guide explains how to use assignment operators and modern methods to modify array values.
Flatten an Array One Level Deep in Javascript
This article explains to flatten an array one level deep in javascript comparing with lodash _.flatten method.