JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Function Closures


📘 JavaScript Closures – Functions Remembering Their Scope

A closure is created when a function retains access to its lexical scope, even after the outer function has finished executing.

In simple terms:

A closure is a function that remembers the variables from its outer function, even after that outer function has returned.


🔹 Example 1 – Basic Closure

function outer() {
  let count = 0;
  return function () {
    count++;
    console.log(count);
  };
}

const counter = outer();
counter(); // 1
counter(); // 2

✅ The inner function "remembers" the count variable even after outer() has finished.


🔹 Example 2 – Multiple Closures

function greet(msg) {
  return function (name) {
    console.log(`${msg}, ${name}`);
  };
}

const sayHi = greet("Hi");
sayHi("Ravi"); // Hi, Ravi
sayHi("Neha"); // Hi, Neha

✅ Each call to greet() creates a new closure with its own msg.


Practice Questions

Q1. Write a function createCounter() that returns another function which increases and returns a private counter each time it's called.

Q2. Create a function greet(message) that returns a function which accepts a name and logs message + name.

Q3. Create a function multiplier(factor) that returns a function to multiply any number by that factor.

Q4. Write a closure that stores a secret message and provides a method to read it but not modify it.

Q5. Create a once() function that allows the given function to run only once and ignores subsequent calls.

Q6. Write a closure that maintains a list and provides addItem() and getItems() methods.

Q7. Create a closure that tracks the number of times a button is clicked (simulate clicks using a function).

Q8. Build a function makeAdder(x) that returns another function which adds x to its argument.

Q9. Create a timer() closure that stores the start time and returns the elapsed time when called again.

Q10. Write a closure-based cache() function that stores and returns computed values based on input (e.g., square of number).


JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top