Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🟨 Days 1–7 – JavaScript Fundamentals  ·  Day 05

Day 5: Functions, Arrow Functions & Scope

⏱ 90 min📶 Beginner🎯 100% self-study
Day 5 / 30

✅ 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

JavaScript
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);
1050 2688 Two items with GST: 1627.5
🧠 return ends the function

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

JavaScript
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 charge
960 2430 540

Three ways to write a function

JavaScript
// 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));
16 27 42 Namaste, Riya! { item: 'Ghewar', qty: 2 }
StyleSyntaxUse for
Declarationfunction name() { }Main named functions in a file
Expressionconst name = function () { }Assigning functions conditionally
Arrow ⭐const name = (a) => a * 2Short helpers and callbacks (map, filter, events)
Methodobj = { total() { } }Functions inside objects/classes (Day 7, 17)

Callbacks: functions as values

JavaScript
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`));      // format
[ 945, 682.5, 735 ] [ 800, 550, 600 ] [ '₹900/kg', '₹650/kg', '₹700/kg' ]
💡 You already used a callback

In 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

JavaScript
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);
Sharma Sweets · INV-1042 undefined undefined

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

HTML + JavaScript
<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>
▶  A pure emi() function + a formatting helper

🏅 Job skills unlocked today

✔ Write functions with parameters, defaults and return✔ Choose declaration, expression or arrow style✔ Pass functions as callbacks✔ Understand scope and write pure functions

Practice tasks

🏋️ Practice – do it yourself

Task 1: Write an arrow function percentage(obtained, total) that returns a number rounded to 1 decimal, and a function result(p) that returns "Distinction" (≥ 75), "First" (≥ 60), "Pass" (≥ 33) or "Fail".
Show solution
JavaScript
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));
}
412 82.4% Distinction 318 63.6% First 210 42% Pass 150 30% Fail
Task 2: Write convertTemp(value, to = "F") that converts Celsius to Fahrenheit or back when to is "C".
Show solution
JavaScript
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));
113 45 -40
Task 3: Create a function formatINR(n) using toLocaleString("en-IN") and use it to print 1234567.8 as ₹12,34,568.

Quick quiz

🧠 Quick Quiz – test yourself

1. A function without return gives…
Default return value.
2. const f = x => x * 2; f(5) is…
Implicit return.
3. Which can be called before its line in the file?
Declarations are hoisted.
4. A function passed to another function is a…
Called back later.
5. A pure function…
No side effects.

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.
➡️ Next

Day 6: arrays – store lists of products, marks and orders and use their everyday methods.

Frequently Asked Questions

How long should a function be?
Ideally it does one job and fits on one screen (often 5–25 lines). If you need the word “and” to describe it, split it.
Why toLocaleString("en-IN")?
It formats numbers the Indian way (12,34,567) – exactly what customers expect on bills.
← JavaScript (30 Days)
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

Next topicDay 6: Arrays and Their Everyday Methods Your progress: 5 / 30 (17%) · Lesson 6 / 30 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free