What's the difference between a method and a function?
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