🧠 1. Function – What is it?
A function is a reusable block of code that performs a task.
✅ Syntax:
function functionName(parameters) {
// code
return result;
}
📌 Example:
function add(a, b) {
return a + b;
}
let result = add(5, 3); // result = 8
console.log(result);
🔁 2. Return Statement
-
return
gives back a value from the function. - It exits the function immediately.
function greet(name) {
return "Hello, " + name;
}
console.log(greet("Sudhakar")); // Hello, Sudhakar
🧰 3. Method – What is it?
A method is a function that belongs to an object.
✅ Syntax:
let obj = {
methodName: function() {
return "I'm a method";
}
};
📌 Example:
let person = {
firstName: "Sudhakar",
greet: function() {
return "Hello, " + this.firstName;
}
};
console.log(person.greet()); // Hello, Sudhakar
⚡ Quick Comparison
Concept | Description | Example |
---|---|---|
Function | Reusable block of code | function sum(a, b) { return a + b; } |
Method | Function inside an object | person.greet = function() { ... } |
💡 More Examples
➤ Arrow Function with Return:
const multiply = (x, y) => x * y;
console.log(multiply(4, 3)); // 12
➤ Function Returning Another Function:
function outer() {
return function inner() {
return "I'm inner";
};
}
let innerFunc = outer();
console.log(innerFunc()); // I'm inner
Top comments (0)