MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Closures Introduction0%
Study Materials
JavaScript for IntermediateProgress 0%
1.1Block Scope with let & const1.2Template Literals1.3Destructuring Arrays and Objects1.4Default Parameters1.5Enhanced Object Literals
2.1Arrow Functions Advanced2.2Rest & Spread Operators2.3Closures Introduction2.4Immediately Invoked Functions (IIFE)
HomeTutorialsJavaScript for IntermediateClosures Introduction
Immediately Invoked Functions (IIFE)

Closures Introduction

Beginner12 min read•Updated: 2026-09-15•By Er. Sumit Kumar (MSK Institute)
Study Materials

A Closure is one of the most powerful and fundamental concepts in JavaScript. A closure is the combination of a function bundled together with references to its surrounding lexical state (the lexical environment). In simple terms: a closure gives a function access to its outer scope even after the outer function has finished executing!


1. How Closures Work Under the Hood

Normally, when a function finishes executing, its local variables are removed from the Call Stack and garbage collected.

However, if an inner function references variables from the outer function, JavaScript preserves the outer scope in memory as long as the inner function is alive:

1function createGreeter(greeting) {
2 // 'greeting' is a local variable inside createGreeter
3 
4 return function(name) {
5 // Inner function accesses 'greeting' from the parent scope:
6 console.log(`${greeting}, ${name}!`);
7 };
8}
9 
10// createGreeter finishes executing and returns:
11const sayHello = createGreeter("Hello");
12const sayNamaste = createGreeter("Namaste");
13 
14// The returned functions still REMEMBER their original greeting!
15sayHello("Sumit"); // "Hello, Sumit!"
16sayNamaste("Aarav"); // "Namaste, Aarav!"

2. Practical Application: Private Variables (Data Encapsulation)

JavaScript historically did not have private class fields. Closures provided the standard way to create private, encapsulated state:

1function createBankAccount(initialBalance) {
2 let balance = initialBalance; // Private variable! Not directly accessible from outside!
3 
4 return {
5 deposit(amount) {
6 if (amount > 0) {
7 balance += amount;
8 console.log(`Deposited ₹${amount}. New balance: ₹${balance}`);
9 }
10 },
11 withdraw(amount) {
12 if (amount <= balance) {
13 balance -= amount;
14 console.log(`Withdrew ₹${amount}. New balance: ₹${balance}`);
15 } else {
16 console.log("Insufficient funds!");
17 }
18 },
19 getBalance() {
20 return balance;
21 }
22 };
23}
24 
25const myAccount = createBankAccount(1000);
26myAccount.deposit(500); // Deposited ₹500. New balance: ₹1500
27console.log(myAccount.balance); // undefined! (Direct access is impossible!)
28console.log(myAccount.getBalance()); // 1500 (Accessible only through closures!)

3. Function Factories

A closure allows you to create customizable function generators:

1function createMultiplier(multiplier) {
2 return function(x) {
3 return x * multiplier;
4 };
5}
6 
7const double = createMultiplier(2);
8const triple = createMultiplier(3);
9 
10console.log(double(10)); // 20
11console.log(triple(10)); // 30

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What is a closure in JavaScript?
Question 2
Why are closures used to create "private variables" in JavaScript?
Question 3
What is the output of:
JavaScriptCode Snippet
1function counter() {
2 let count = 0;
3 return () => ++count;
4}
5const c1 = counter();
6c1();
7console.log(c1());
Question 4
Do separate instances of a function factory share the same closure state?
Question 5
Can closures cause memory leaks if misused?
Next Lesson

Immediately Invoked Functions (IIFE)

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Rest & Spread OperatorsImmediately Invoked Functions (IIFE)

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master JavaScript for Intermediate with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext