Closures In Javascript

Closures In Javascript

The Tricky Concept

Basic Definition

In JavaScript, closures refer to the ability of a function to access variables from its outer or parent function, even after that function has returned. This is possible because the inner function maintains a reference to the variables of the outer function, even if the outer function has already finished executing.

function outerFunction() {
  let counter = 0;

  function innerFunction() {
    counter++;
    return counter
  }

  return innerFunction;
}

const closure = outerFunction();

console.log(closure()) // 1 
console.log(closure()) // 2
console.log(closure()) // 3

A Simpler Way

Closures allow a function to access variables from an outer function even after the outer function has returned. This is possible because the inner function has access to the outer function's scope, which includes its variables and parameters. Closures are created when a function is defined inside another function, and the inner function references variables from the outer function's scope.

A Funny Way

Have you ever had a friend who just won't let go? Like, you tell them a secret or a joke and they keep bringing it up, even weeks or months later? That's kind of like closure in JavaScript.

When you create a closure, you're defining a function inside another function. The inner function "remembers" the variables from the outer function's scope, even after the outer function has been completed. So, it's kind of like your friend who just won't forget that embarrassing story you told them last year.

Ending Note

Closures can be useful, too! They allow you to create functions with "private" variables, which can't be accessed from outside the function. It's like having a secret code that only your inner function knows, and your outer function is the bouncer who keeps everyone else out.

Did you find this article valuable?

Support Sandeep Rana by becoming a sponsor. Any amount is appreciated!