JavaScript Closure function

Introduction

The closure function is part of advanced JavaScript. It is used to access outer function parameters and variables in the inner function, so the inner function is called a closure.
The inner function returns to the outer function.

What is a Closure?

A closure is a function that remembers and can access variables from its outer (parent) scope, even after the outer function has finished executing.

In simple words:

 A closure “closes over” the variables of its parent function.

📖
Best Practices:
  • Use closures for private variables.
  • Use let instead of var in loops.
  • Release references when not needed.

Basic Example


function outer() {
   let message = "Hello";
   function inner() {
       console.log(message);
   }
   return inner;
}
const func = outer();
func(); 

Output:

Hello

Note:  Even though outer() has finished execution, inner() still remembers the message.

Example 2:

Suppose you have an outer function start() and declared the employeeName variable in this, and called this variable in the displayEmployeeName() inner function.


function start() {
  var employeeName = 'John'; 
  function displayEmployeeName() { 
    console.log("Hello "+employeeName); 
  }
  displayEmployeeName();
}
start();

Output:

Hello John

Example 3:

Suppose you change the outer scope variable x value in the inner function scope, then the value will be changed.


// declaration in outer scope
var x = 5; 
function getNum() {
console.log(x); // outer scope is captured on declaration
}
getNum(); 

Output:

5

Example 4:

Suppose you change the outer scope variable x value in the inner function scope, then the value will be changed.


var x = 5; // declaration in outer scope
function getNum() {
x=2;
console.log(x); // outer scope is captured on declaration
}
getNum(); 

Output:

2

How Closures Work

Closures rely on lexical scope, which means functions remember where they were defined.

You will see the steps of Closure work.

  1. A function is created inside another function
  2. The inner function accesses variables from the outer function
  3. The inner function is returned or used later
  4. The variables remain accessible even after the outer function execution

Real-Life Examples

You will see some Real Life Examples.

1. Counter Function

Example:


function counter() {
   let count = 0;

   return function() {
       count++;
       return count;
   };
}

const c = counter();
console.log(c());
console.log(c()); 

Output:

1
2

2. Multiplication of Numbers


function multiplier(factor) {
   return function(num) {
       return num * factor;
   };
}

const double = multiplier(2);
console.log(double(5));

Output:

10

Closure vs Global Variables

Closures provide a safer alternative to global variables.

Feature Closure Global Variable
Scope Private Public
Security High Low
Maintainability Better Poor

Common Mistakes

Many Beginners do below common mistakes.

1. Confusing Scope


function test() {
   let x = 10;
}
console.log(x); 

Output:

ReferenceError: x is not defined

2. Loop Issues


for (var i = 0; i < 3; i++) {
   setTimeout(function() {
       console.log(i); 
   }, 1000);
}

Output:

3
3
3

Fix:


for (let i = 0; i < 3; i++) {
   setTimeout(function() {
       console.log(i); 
   }, 1000);
}

Output:

0
1
2

Advantages of Closures

There are some advantages of Closures

  1. Data privacy
  2. Persistent state
  3. Cleaner code
  4. Functional programming support
  5. Reusability

Disadvantages of Closures

There are some disadvantages of Closures

  1. Memory consumption
  2. Harder to debug for beginners
  3. Overuse can complicate code

Javascript Closure function – Interview Questions

Q 1: What is closure?
Ans: Function remembering its outer variables.
Q 2: Why closures are used?
Ans: Data encapsulation.
Q 3: Do closures store variables?
Ans: Yes.
Q 4: Are closures memory-heavy?
Ans: They can be if misused.
Q 5: Example use?
Ans: Private variables.

Javascript Closure function – Objective Questions (MCQs)

Q1. A closure is created when a function ______.






Q2. Closures allow access to ______ variables.






Q3. Closures are commonly used for ______.






Q4. Variables in closures are preserved in ______.






Q5. Which feature enables closures?






Conclusion

Closures are one of the most powerful features in JavaScript that allow functions to remember and access variables from their outer scope. They play a crucial role in modern JavaScript development, enabling patterns like data encapsulation, memoization, and function factories.