Functions, Modern Arrow Functions & Callbacks
1. Simple Definition
Function ek reusable code ka block hota hai jo ek specific task perform karta hai. Aap function ko input (parameters) dete hain, wo andar calculation karta hai, aur output result (return) wapas karta hai. Modern JavaScript me Arrow Functions (() =>) functions ko chota aur clean banate hain.
2. Real-Life Analogy
Juice mixer ko imagine kijiye:
• Parameters (Input): Aapne mixer me fruits (Mango/Apple) daale.
• Function Body: Machine ne blade ghuma kar crush kiya.
• Return Value (Output): Machine ne glass me fresh juice nikal kar return kiya!
Machine ko aap din me 100 baar alag fruits dekar reuse kar sakte hain!
3. Why Do We Need It?
DRY Principle (Don't Repeat Yourself): Agar aapko discount calculate karne ka 10-line ka formula chahiye, toh use 10 jagah copy-paste karne ke badle ek function me daalte hain aur jahan zarurat ho wahan call karte hain.
4. Syntax: 3 Ways to Write Functions
// 1. Traditional Function Declaration (Hoisted!)
function addNumbers(a, b) {
return a + b;
}
// 2. Function Expression
const multiply = function(a, b) {
return a * b;
};
// 3. Modern ES6 Arrow Function (Clean & Concise!)
const subtract = (a, b) => a - b; // Implicit Return
// 4. Default Parameters & Rest Parameters (...args)
const calculateBill = (total, taxRate = 0.18, ...discounts) => {
let discountTotal = discounts.reduce((acc, d) => acc + d, 0);
return (total - discountTotal) * (1 + taxRate);
};
5. Basic Example (Arrow Functions & Callbacks)
// Higher-Order Function accepting a Callback
function processPayment(amount, onSuccess) {
console.log(`Processing payment of ₹${amount}...`);
// Simulating payment success callback
onSuccess(`Payment Receipt: TXN_${Date.now()}`);
}
// Calling with Arrow Callback
processPayment(1499, (receiptId) => {
console.log(`Success! Transaction ID: ${receiptId}`);
});
6. Output / Expected Result
7. Code Explanation
return: Function execution ko khatam karta hai aur value wapas bhejta hai. Agar return na likhein toh functionundefinedreturn karta hai.- Implicit Return: Arrow function me agar curly braces
{}na hon, toh=>ke aage likhi value automatically return ho jati hai:(x, y) => x + y. - Callback: Aisa function jo kisi doosre function ke andar as an argument pass kiya jata hai taaki baad me call kiya ja sake (events aur async programming ka base!).
- Rest Parameters (
...args): Unlimited arguments ko ek single array me collect kar leta hai.
8. Real-World Example
Button click listeners: button.addEventListener("click", () => { alert("Submitted!"); }); me arrow function ek callback hai jo click hone par trigger hota hai.
9. Common Mistakes
Arrow functions ka apna koi this nahi hota; wo apne surrounding lexical scope ka this inherit karte hain. Isliye object ke methods likhte waqt arrow functions use karne se this.name undefined ho sakta hai!
10. Best Practices
- Pure callbacks aur short logic ke liye Arrow functions use karein.
- Har function ka sirf ek single, focused purpose hona chahiye (Single Responsibility Principle).
11. Try It Yourself
Playground me ek function banayein jo Celsius ko Fahrenheit me convert kare: (c) => (c * 9/5) + 32.
12. Challenge
Ek closure function createCounter() banayein jo ek function return kare jo har baar call hone par count 1 badhata jaye.
13. Interview Questions
Answer: Closure tab banta hai jab ek inner function apne parent (outer) function ke variables ko yaad rakhta hai, bhale hi outer function execute hokar close ho chuka ho! Ye private variables banane aur data privacy maintain karne ke liye use hota hai.
14. Quick Revision
const fn = () => ...= Modern arrow function.returngives output to the caller.- Callbacks are functions passed as arguments.
- Closures remember their parent's scope.
15. FAQ
Q1. Function Declaration aur Expression me hoisting ka kya fark hai?
function myFn() { ... } poora hoist hota hai (declare hone se pehle bhi call kar sakte hain). Function expression (const myFn = ...) hoist nahi hota (TDZ error aayega).
Q2. IIFE kya hota hai?
Immediately Invoked Function Expression: (function() { ... })(); — banate hi turant execute hone wala self-executing function.
Q3. Pure Function kya hota hai?
Aisa function jo same input par hamesha exact same output de aur bahar ke kisi global variable ko mutate na kare (No side-effects).
Q4. Arrow function me single parameter par brackets optional hain?
Haan! x => x * 2 bina brackets ke valid hai. Lekin zero ya multiple params par () compulsory hote hain.
Q5. Default parameter kab trigger hota hai?
Jab caller argument pass na kare ya strictly undefined pass kare.
Functions, Modern Arrow Functions & Callbacks
1. Simple Definition
A Function is a reusable block of organized instructions designed to perform a dedicated computation or action. Modern JavaScript uses Function Declarations, Function Expressions, concise Arrow Functions (=>), and Callbacks (functions passed as arguments to other functions).
2. Real-Life Analogy
You insert coffee beans and milk (Parameters / Arguments), the machine runs heating and brewing routines (Function Body), and dispenses a hot cup of cappuccino (Return Value). Whenever you want coffee, you just tap the button (Function Invocation) rather than building a fresh heater from scratch!
3. Function Declarations vs Arrow Functions
| Feature | Function Declaration | Arrow Function (=>) |
|---|---|---|
| Syntax | function calculateTotal(a, b) { ... } |
const calculateTotal = (a, b) => a + b; |
| Hoisting | Hoisted (Callable before definition) | Not hoisted (Follows variable declaration) |
this Binding |
Dynamic (depends on how it's called) | Lexical (inherits from surrounding scope) |
| Arguments Object | Has arguments object |
No arguments (use rest ...args) |
4. Callback Functions & Higher-Order Functions
// Callback function: A function passed into another function
function fetchUserData(userId, callback) {
console.log("Fetching user from database...");
const user = { id: userId, name: "Kabir", role: "DevOps" };
callback(user); // Invoking the callback
}
fetchUserData(101, (user) => {
console.log("User successfully loaded:", user.name);
});
5. Default Parameters & Rest Operator
// Default parameter fallback + Rest parameters (...numbers)
function sumAll(initialBonus = 0, ...numbers) {
return numbers.reduce((acc, curr) => acc + curr, initialBonus);
}
sumAll(10, 1, 2, 3); // 10 + 1 + 2 + 3 = 16
6. Common Mistakes
Writing const getUser = () => { name: "Raj" }; treats the curly braces as a function body, returning undefined! Wrap the object in parentheses: const getUser = () => ({ name: "Raj" });!
7. Best Practices
- Use Arrow Functions for concise callbacks and array transformations.
- Keep functions small and focused on a single responsibility (Single Responsibility Principle).
- Use Rest parameters (
...args) instead of the legacyargumentsobject.
8. Practice Exercise
Create an arrow function applyDiscount(price, discountPercent = 10) that calculates the final discounted price and rounds it to two decimal places.
9. Interview Questions
Answer: Standard functions create their own this context depending on the caller. Arrow functions do not bind their own this; they capture the this value of the enclosing execution context at definition time.
10. Summary / Cheat Card
- Arrow functions provide concise syntax with lexical
this. - Wrap implicit return objects in parentheses:
() => ({}). - Callbacks empower event handling, timers, and asynchronous workflows.
11. FAQ
Q1. Can arrow functions be used as constructors?
No, calling new ArrowFunc() throws a TypeError because arrow functions lack a [[Construct]] method and prototype.