Unit 2: Functions, Data Structures & ArraysLesson #3 / 10

Lesson 3: Functions, Scope & Closures

Er. Manoj Kumar — AuthorEr. Manoj KumarLast Updated: 26 Aug, 2026

1. Function Declarations vs Arrow Functions

  • Function Declaration: Hoisted and available throughout the surrounding function scope.
  • ES6 Arrow Function (const fn = (a, b) => a + b;): Concise syntax that lexically binds this.
  • HTML5 Web Code (index.html)
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>JS Functions & Closures</title>
    </head>
    <body style="background:#17181c; color:#fff; font-family:Arial; padding:30px;">
    <h2>Closure Counter Demo</h2>
    <button id="counter-btn" style="padding:10px 20px; background:#04AA6D; color:#fff; border:none; border-radius:6px; font-weight:bold; cursor:pointer;">
    Click Count: 0
    </button>
    <script>
    // Closure Factory Function
    function createCounter() {
    let count = 0; // Private state variable
    return function() {
    count++;
    return count;
    };
    }
    const clickCounter = createCounter();
    const btn = document.getElementById("counter-btn");
    btn.addEventListener("click", () => {
    const currentCount = clickCounter();
    btn.textContent = "Click Count: " + currentCount;
    });
    </script>
    </body>
    </html>

    Interactive Knowledge Check

    Test your understanding of Lesson #3 concepts

    What is a Closure in JavaScript?