Closures in JavaScript ๐Ÿ”

ronak wanjarironak wanjari
2 min read

By Ronak Wanjari | Intern at Devsync


Closures are one of the most powerful and sometimes confusing features in JavaScript. But once you understand them, youโ€™ll unlock a lot of potential in your coding skills!


๐Ÿ”Ž What is a Closure?

A closure is simply a function that remembers the variables from its outer scope even after the outer function has finished executing.

In other words:

Functions can "close over" variables and keep access to them.


๐Ÿง  How Does It Work?

Whenever you create a function inside another function, the inner function has access to:

  1. Its own variables.

  2. Variables of the outer function.

  3. Global variables.

Even if the outer function is done executing, the inner function still remembers the outer variables. That "memory" is what we call a closure.


๐Ÿ”ง Simple Example:

javascriptCopyEditfunction outer() {
  let count = 0;

  function inner() {
    count++;
    console.log(count);
  }

  return inner;
}

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

๐Ÿ‘‰ Even though outer() has already run, the inner() function still has access to count โ€” thanks to closure.


๐ŸŒŸ Why Are Closures Useful?

  • Data Privacy / Encapsulation
    You can hide variables from the outside world.

  • Function Factories
    You can create multiple customized functions.

  • Callback Functions & Event Handlers
    Closures are heavily used in asynchronous code.


๐Ÿ”’ Real-Life Usage Example

javascriptCopyEditfunction createPasswordManager(password) {
  return {
    checkPassword: function(input) {
      return input === password;
    }
  }
}

const manager = createPasswordManager("mySecret");
console.log(manager.checkPassword("wrong"));  // false
console.log(manager.checkPassword("mySecret"));  // true

Here, password is completely private โ€” nobody can access it directly from outside the function. Closure helps us build this kind of private data protection.

๐Ÿ”‘ Quick Summary

  • Closure = Function + its Lexical Environment.

  • Functions remember the variables where they were created.

  • Powerful for data privacy, async programming, and interview questions!


๐Ÿš€ Iโ€™m currently learning JavaScript as part of my internship at Devsync , and closures were one of the most mind-blowing topics I came across!

0
Subscribe to my newsletter

Read articles from ronak wanjari directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

ronak wanjari
ronak wanjari