Do you know Closure in JavaScript ?
Mohammad Aman

Mohammad Aman @mohammad1105

About: Developer | CS Enthusiast passionate about creating efficient, modern, user-centric applications.

Location:
India
Joined:
Jan 5, 2024

Do you know Closure in JavaScript ?

Publish Date: Jan 5 '24
24 5

First of All, if you are a newbie and don't know What is JavaScript ?

JavaScript is a programming language primarily used for creating interactive web pages. It breathes life into static HTML, adding animations, dynamic content, and user interaction. Think of it as the bridge between the user and the website, making the browsing experience engaging and responsive.
According to several surveys, JavaScript currently holds the title of the most popular programming language in the world, with a vast user base and constantly evolving ecosystem.

And if you are familiar with JavaScript then you should must know what is closure in JavaScript

  • What is a Closure ? A closure is the combination of a function and its associated lexical environment. The lexical environment encompasses the variables, functions, and objects that were in scope when the function was created. This "enclosed" environment persists even after the outer function has finished executing, allowing the inner function to access and modify these variables
function createCounter() {
  let count = 0; // Outer function variable

  return function() {
    count++; // Inner function can access and modify count
    return count;
  };
}

const counter = createCounter(); // Get a new counter function

console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3

Enter fullscreen mode Exit fullscreen mode

Explanation:

  1. createCounter createCounter defines an outer function with a count variable.
  2. It returns an inner function (the closure) that has access to count.
  3. counter stores a reference to the returned inner function.
  4. Each time counter() is called, it increments and returns the shared count value.

Real-world applications:

  • Module patterns: Creating private variables and methods within modules to maintain encapsulation and avoid naming conflicts.

  • Event handlers: Preserving state information between events (e.g., a button click counter).

  • Callbacks: Passing data to functions that will be executed later (e.g., asynchronous operations).

  • Partial application: Creating new functions with pre-filled arguments (e.g., a function that always greets a specific person).

  • Timers: Scheduling functions to run after a delay (e.g., animation effects).

  • Custom iterators: Implementing custom iteration logic for data structures (e.g., generators).

Key takeaways:

  • Closures allow functions to "remember" and access variables from their enclosing scope, even after the outer function has finished.
  • They are a powerful tool for creating private state, managing data, and implementing modular code structures.
  • Understanding closures is essential for writing more sophisticated and reusable JavaScript applications.

Comments 5 total

  • Jon Randy 🎖️
    Jon Randy 🎖️Jan 5, 2024

    A closure is a function that has access to variables in its outer (enclosing) function's scope...

    Unfortunately this is not correct...

    • Closures are not functions
    • ALL functions have access to their surrounding scope (which is more than just the scope of the outer function, if indeed an outer function even exists)
    • Mohammad Aman
      Mohammad AmanJan 5, 2024

      Thank you for the correct information. Actually i forgot while writing this post.
      'A closure is the combination of a function bundled together'
      I will correct my post
      Thank you 😊❤️

  • NotFound404
    NotFound404Jan 5, 2024

    A closure is a programmable scope where functions only change variables with the scope.

    • NotFound404
      NotFound404Jan 5, 2024

      a closure is not a function. just because in javascript a function can be a closure. You are totally mistaking one thing for another.

Add comment