Day 5: Functions, Arrow Functions & Scope
✅ Today you will learn
- Why functions: write once, use everywhere
- Parameters, arguments, default values and return
- Function declarations vs expressions vs arrow functions
- Callbacks – passing a function to another function
- Scope and pure functions
🏢 In the real world
GST is calculated on the cart page, the invoice page and the WhatsApp message. If the logic is copy-pasted three times and the GST rate changes, someone will forget one copy and customers get different totals. A function keeps the rule in one place – change it once, it is right everywhere.
Declaring and calling a 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);Code after return never runs. A function without return gives back undefined – a common reason for “my total shows undefined”.
Default values and many 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 chargeThree ways to write a function
// 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));| Style | Syntax | Use for |
|---|---|---|
| Declaration | function name() { } | Main named functions in a file |
| Expression | const name = function () { } | Assigning functions conditionally |
| Arrow ⭐ | const name = (a) => a * 2 | Short helpers and callbacks (map, filter, events) |
| Method | obj = { total() { } } | Functions inside objects/classes (Day 7, 17) |
Callbacks: functions as values
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`)); // formatIn button.addEventListener("click", function () { … }) the function is a callback: the browser calls it later, when the click happens. Callbacks power events, array methods (Day 8) and timers (Day 19).
Scope: where a variable lives
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
- Changes outside variables
- Result depends on hidden state
- let total = 0; function add(x) { total += x }
- Hard to test
Pure function ⭐
- Uses only its parameters
- Same input → same output
- const add = (total, x) => total + x
- Easy to test and reuse
Real task: an 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 unlocked today
Practice tasks
🏋️ Practice – do it yourself
Show 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));
}Show 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 – test yourself
Interview corner
💼 Interview Corner
Arrow functions vs regular functions?
Arrow functions are shorter, have no own this/arguments (they use the surrounding this), cannot be used as constructors with new and are not hoisted like declarations. Use them for callbacks; use regular functions/methods when you need your own this.
What is a callback and where is it used?
A function passed as an argument to be called later by the receiving code – event listeners, array methods (map, filter), timers (setTimeout) and older async APIs.
Summary
- function name(params) { return value; } – call with name(args).
- Default parameters handle missing arguments.
- Arrow functions for short helpers and callbacks.
- Keep functions small, pure and in one place.
Day 6: arrays – store lists of products, marks and orders and use their everyday methods.
