Free tutorials & notes in Hindi & English · Clean code examples 🧰 मुफ़्त PDF और फ़ोटो टूल्स →
🟨 Days 1–7 – JavaScript की नींव  ·  दिन 05

दिन 5: Functions, Arrow Functions और Scope

⏱ 90 min📶 Beginner🎯 100% self-study
दिन 5 / 30

✅ आज आप सीखेंगे

  • 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 बनाना और बुलाना

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 function ख़त्म करता है

return के बाद का code कभी नहीं चलता। बिना return वाला function undefined लौटाता है – “मेरा total undefined दिखाता है” का आम कारण।

Default values और कई 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

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 }
शैलीSyntaxकब
Declarationfunction name() { }File के मुख्य named functions
Expressionconst name = function () { }शर्त के साथ functions assign करना
Arrow ⭐const name = (a) => a * 2छोटे helpers और callbacks (map, filter, events)
Methodobj = { total() { } }Objects/classes के अंदर functions (Day 7, 17)

Callbacks: values के रूप में functions

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' ]
💡 आप callback पहले ही इस्तेमाल कर चुके

button.addEventListener("click", function () { … }) में function एक callback है: browser इसे बाद में, click होने पर बुलाता है। Callbacks events, array methods (Day 8) और timers (Day 19) चलाते हैं।

Scope: variable कहाँ रहता है

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

  • बाहर के 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

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

✔ Parameters, defaults और return वाले functions✔ Declaration, expression या arrow शैली चुनना✔ Functions को callbacks के रूप में देना✔ Scope समझना और pure functions लिखना

Practice tasks

🏋️ Practice – ख़ुद करें

Task 1: Arrow function percentage(obtained, total) लिखें जो 1 decimal तक round number लौटाए, और result(p) जो "Distinction" (≥ 75), "First" (≥ 60), "Pass" (≥ 33) या "Fail" लौटाए।
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: convertTemp(value, to = "F") लिखें जो Celsius को Fahrenheit में या to "C" होने पर उल्टा बदले।
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: toLocaleString("en-IN") से formatINR(n) function बनाएँ और 1234567.8 को ₹12,34,568 print करें।

Quick quiz

🧠 Quick Quiz – ख़ुद को जाँचें

1. बिना return वाला function देता है…
Default return value।
2. const f = x => x * 2; f(5) है…
Implicit return।
3. File में अपनी line से पहले कौन बुलाया जा सकता है?
Declarations hoist होते हैं।
4. दूसरे function को दिया गया function है…
बाद में बुलाया जाता है।
5. Pure function…
कोई side effects नहीं।

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 इस्तेमाल करें।

अक्सर पूछे जाने वाले प्रश्न (FAQ)

Function कितना लंबा हो?
आदर्श रूप से एक काम करे और एक screen में आए (अक्सर 5–25 lines)। वर्णन में “और” लगे तो बाँट दें।
toLocaleString("en-IN") क्यों?
यह numbers को Indian तरीक़े (12,34,567) से दिखाता है – bills पर customers यही उम्मीद करते हैं।
← JavaScript (30 Days)
🔗

Share this topic with a friend

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

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

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

अगला topicदिन 6: Arrays और उनके रोज़ के Methods आपकी प्रगति: 5 / 30 (17%) · Lesson 6 / 30 आगे बढ़ें →

यह lesson कैसा लगा?

आपकी राय से हम content और बेहतर बनाते हैं।

अपना review और सुझाव लिखें (वैकल्पिक)

Review approve होने के बाद आपका नाम और शहर इसके साथ public दिख सकते हैं। Email या phone न लिखें।

▶ CodingEasily on YouTube

Video से सीखें – आसान Hindi में

चुनी हुई video: RDBMS भाग 3 – Class XI Commerce IT

▶ Channel subscribe करें