दिन 5: Functions, Arrow Functions और Scope
✅ आज आप सीखेंगे
- Functions क्यों: एक बार लिखो, हर जगह इस्तेमाल
- Parameters, arguments, default values और return
- Function declarations बनाम expressions बनाम arrow functions
- Callbacks – एक function दूसरे को देना
- Scope और pure functions
🏢 असली दुनिया में
GST cart page, invoice page और WhatsApp message तीनों पर गिना जाता है। अगर logic तीन बार copy-paste हुआ और GST rate बदला, तो कोई एक copy भूल जाएगा और customers को अलग totals मिलेंगे। Function नियम को एक जगह रखता है – एक बार बदलो, हर जगह सही।
Function बनाना और बुलाना
function addGst(amount, rate) { // amount, rate = parameters
const gst = amount * rate / 100;
return amount + gst; // send a value back
}
console.log(addGst(1000, 5)); // 1000, 5 = arguments
console.log(addGst(2400, 12));
const bill = addGst(900, 5) + addGst(650, 5);
console.log('Two items with GST:', bill);return के बाद का code कभी नहीं चलता। बिना return वाला function undefined लौटाता है – “मेरा total undefined दिखाता है” का आम कारण।
Default values और कई parameters
function price(kg, ratePerKg, discountPercent = 0, deliveryCharge = 60) {
const amount = kg * ratePerKg * (1 - discountPercent / 100);
const delivery = amount >= 1500 ? 0 : deliveryCharge;
return Math.round(amount + delivery);
}
console.log(price(1, 900)); // defaults used
console.log(price(3, 900, 10)); // 10% off, free delivery
console.log(price(1, 500, 0, 40)); // custom delivery chargeFunction लिखने के तीन तरीक़े
// 1. Declaration – can be called before it appears (hoisted)
function square(n) { return n * n; }
// 2. Expression – stored in a variable
const cube = function (n) { return n * n * n; };
// 3. Arrow function – short, modern
const double = (n) => n * 2; // implicit return for one expression
const greet = name => `Namaste, ${name}!`;
const makeOrder = (item, qty) => ({ item, qty }); // returning an object needs ( )
console.log(square(4), cube(3), double(21));
console.log(greet('Riya'));
console.log(makeOrder('Ghewar', 2));| शैली | Syntax | कब |
|---|---|---|
| Declaration | function name() { } | File के मुख्य named functions |
| Expression | const name = function () { } | शर्त के साथ functions assign करना |
| Arrow ⭐ | const name = (a) => a * 2 | छोटे helpers और callbacks (map, filter, events) |
| Method | obj = { total() { } } | Objects/classes के अंदर functions (Day 7, 17) |
Callbacks: values के रूप में functions
function applyToAll(prices, rule) { // rule is a callback
const result = [];
for (const p of prices) result.push(rule(p));
return result;
}
const prices = [900, 650, 700];
console.log(applyToAll(prices, p => p * 1.05)); // add 5% GST
console.log(applyToAll(prices, p => p - 100)); // festival ₹100 off
console.log(applyToAll(prices, p => `₹${p}/kg`)); // formatbutton.addEventListener("click", function () { … }) में function एक callback है: browser इसे बाद में, click होने पर बुलाता है। Callbacks events, array methods (Day 8) और timers (Day 19) चलाते हैं।
Scope: variable कहाँ रहता है
const SHOP = 'Sharma Sweets'; // global – visible everywhere
function invoiceHeader(no) {
const prefix = 'INV'; // local – only inside this function
return `${SHOP} · ${prefix}-${no}`;
}
console.log(invoiceHeader(1042));
console.log(typeof prefix); // 'undefined' – prefix is not visible here
if (true) {
const insideBlock = 'block scoped';
}
console.log(typeof insideBlock);Impure function
- बाहर के variables बदलता है
- नतीजा छिपी state पर निर्भर
- let total = 0; function add(x) { total += x }
- Test करना मुश्किल
Pure function ⭐
- सिर्फ़ अपने parameters
- वही input → वही output
- const add = (total, x) => total + x
- Test और reuse आसान
असली task: EMI calculator
<label>Loan ₹ <input id="p" type="number" value="500000"></label><br>
<label>Interest % per year <input id="r" type="number" value="9.5" step="0.1"></label><br>
<label>Months <input id="n" type="number" value="60"></label><br>
<button id="go">Calculate EMI</button>
<p id="out"></p>
<script>
// EMI = P × r × (1 + r)^n / ((1 + r)^n − 1), r = monthly rate
function emi(principal, yearlyRate, months) {
const r = yearlyRate / 12 / 100;
if (r === 0) return principal / months;
const f = (1 + r) ** months;
return principal * r * f / (f - 1);
}
const rupees = n => '₹' + Math.round(n).toLocaleString('en-IN');
document.querySelector('#go').addEventListener('click', () => {
const P = Number(document.querySelector('#p').value);
const R = Number(document.querySelector('#r').value);
const N = Number(document.querySelector('#n').value);
const monthly = emi(P, R, N);
document.querySelector('#out').innerHTML =
`EMI <b>${rupees(monthly)}</b> · total paid ${rupees(monthly * N)} · interest ${rupees(monthly * N - P)}`;
});
</script>🏅 आज के Job Skills
Practice tasks
🏋️ Practice – ख़ुद करें
Solution देखें
const percentage = (obtained, total) => Math.round(obtained / total * 1000) / 10;
function result(p) {
if (p >= 75) return 'Distinction';
if (p >= 60) return 'First';
if (p >= 33) return 'Pass';
return 'Fail';
}
for (const marks of [412, 318, 210, 150]) {
const p = percentage(marks, 500);
console.log(marks, p + '%', result(p));
}Solution देखें
function convertTemp(value, to = 'F') {
return to === 'F' ? value * 9 / 5 + 32 : (value - 32) * 5 / 9;
}
console.log(convertTemp(45), convertTemp(113, 'C'), convertTemp(-40));Quick quiz
🧠 Quick Quiz – ख़ुद को जाँचें
Interview corner
💼 Interview Corner
Arrow functions बनाम regular functions?
Arrow functions छोटे हैं, उनका अपना this/arguments नहीं (आसपास का this लेते हैं), new के साथ constructor नहीं बनते और declarations जैसे hoist नहीं होते। Callbacks के लिए लें; जब अपना this चाहिए तब regular functions/methods।
Callback क्या है और कहाँ इस्तेमाल होता है?
Argument के रूप में दिया गया function जिसे लेने वाला code बाद में बुलाता है – event listeners, array methods (map, filter), timers (setTimeout) और पुराने async APIs।
सारांश
- function name(params) { return value; } – name(args) से बुलाएँ।
- Default parameters ग़ायब arguments संभालते हैं।
- छोटे helpers और callbacks के लिए arrow functions।
- Functions छोटे, pure और एक जगह रखें।
Day 6: arrays – products, marks और orders की lists रखें और उनके रोज़ के methods इस्तेमाल करें।
