Deep Gandhi
deepgandhi000@gmaol.com
JavaScript
Function VS Method
What is a function?
A function is a block of reusable code that performs a specific
task.
Functions can take input parameters and can return a value.
Functions are defined outside of objects.
Ex;
function add(a, b) {
return a + b;
}
console.log(add(2, 3)); // Outputs: 5
2
Key Characteristics:
Independent of any object.
Can be called from anywhere in the code, provided they are in
scope.
Do not have a context (this).
What is a Method?
A method is a function that is associated with an object.
Methods are properties of objects and are defined within the
context of the object.
Ex;
const calculator = {
add: function(a, b) {
return a + b;
}
};
console.log(calculator.add(2, 3)); // Outputs: 5
3
Key Characteristics:
Belong to objects.
Can access and modify the object’s properties.
Have a context (this) that refers to the object they belong to.
Differences
Association:
Function: Independent of objects.
Method: Tied to objects.
Context (this):
Function: No implicit context.
Method: Implicit context (this) which refers to the object it
belongs to.
Usage:
Function: General-purpose and can be used anywhere.
Method: Used to perform operations on object data or interact
with object properties.
4
Ex;
// Function
function greet() {
return "Hello";
}
console.log(greet()); // Outputs: Hello
// Method
const person = {
name: "Deep",
greet: function() {
return "Hello, " + this.name;
}
};
console.log(person.greet()); // Outputs: Hello, Deep
Practical Usage
Functions:
Utility code that can be reused across different parts of a
program.
Performing operations that do not depend on or modify object
states.
5
Methods:
Encapsulating behavior that operates on the data contained in an
object.
Interacting with or manipulating an object's properties.
Functions and Methods in Classes (ES6)
In modern JavaScript (ES6 and later), functions and methods are
used within classes to define the behavior of objects instantiated
from those classes.
Ex;
class Person {
constructor(name) {
this.name = name;
}
// Method
greet() {
return `Hello, ${this.name}`;
}
6
// Static Function
static staticGreet() {
return 'Hello';
}
}
const person1 = new Person('Deep');
console.log(person1.greet()); // Outputs: Hello, Deep
console.log(Person.staticGreet()); // Outputs: Hello