Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is the difference between a method and a function?
In this article, we will learn about the difference between a method and a function in JavaScript. While both execute code blocks, the key difference is that a function is standalone code, while a method is a function that belongs to an object.
What is a Function?
A function is a reusable block of code that can be called anywhere in your program. Functions help create modular code by eliminating repetition.
JavaScript functions can be defined using function expressions, arrow functions, or the function keyword.
Syntax
function functionName(parameter1, parameter2) {
// code to be executed
return value; // optional
}
Example
function greet(name) {
return "Hello, " + name + "!";
}
// Function call
let message = greet("Bob");
console.log(message);
Hello, Bob!
What is a Method?
A method is a function that belongs to an object. It's a property of an object that contains a function definition. Methods can access and modify the object's properties using the this keyword.
Methods are fundamental in object-oriented programming for defining object behavior.
Example
let person = {
name: 'Alice',
age: 25,
greet: function() {
return 'Hello, I am ' + this.name + ' and I am ' + this.age + ' years old.';
},
celebrateBirthday: function() {
this.age++;
return 'Happy birthday! Now I am ' + this.age + '.';
}
};
console.log(person.greet());
console.log(person.celebrateBirthday());
Hello, I am Alice and I am 25 years old. Happy birthday! Now I am 26.
Key Differences
| Feature | Function | Method |
|---|---|---|
| Definition | Standalone block of code | Function that belongs to an object |
| Invocation | functionName() |
object.methodName() |
| Context | No implicit this binding |
this refers to the owner object |
| Usage | General-purpose, reusable operations | Defines object-specific behavior |
Converting Functions to Methods
Any function can become a method when assigned to an object property:
// Standalone function
function sayGoodbye() {
return "Goodbye!";
}
// Convert to method
let obj = {
farewell: sayGoodbye
};
console.log(sayGoodbye()); // Function call
console.log(obj.farewell()); // Method call
Goodbye! Goodbye!
Conclusion
Functions are independent code blocks, while methods are functions attached to objects. Understanding this distinction is crucial for effective JavaScript programming and object-oriented design.
