DEV Community

Cover image for A Practical Introduction to Closures in JavaScript
Diego Palacios Lepore
Diego Palacios Lepore

Posted on • Edited on

A Practical Introduction to Closures in JavaScript

Closures are a very interesting topic, and it is a demonstration of how to leverage the lexical scope in JavaScript.

Let's start by showing a code example first:

function outerFunction() {
  let count = 0;

  return function innerFunction() {
   count += 1;
   console.log(`Count is now ${count}`)
  }
}
Enter fullscreen mode Exit fullscreen mode

Before adding more code, I think it is important to mention that when a function is invoked, after doing its stuff and returning its output, all the variables and functions and any data inside that function will be completely gone.

So, one might think that, if that's the case, the count variable will dissapear right after outerFunction is invoked, and the returned function will lose access to the count variable.

But, due to the lexical nature of JavaScript, when a function is created, like innerFunction in this case, it will always be returned along with its scope.

Even after the outerFunction has finished executing, the innerFunction retains access to the variables in its outer scope, allowing it to keep data private and alive throughout the lifecycle of the application.

Let's continue with our example above:

function outerFunction() {
  let count = 0;

  return function innerFunction() {
   count += 1;
   console.log(`Count is now ${count}`)
  }
}

const myFunction = outerFunction() // outerFunction is executed and, and myFunction becomes innerFunction

myFunction() // Count is now 1
myFunction() // Count is now 2
myFunction() // Count is now 3
Enter fullscreen mode Exit fullscreen mode

So basically functions can carry with them the scope in which they were created. This includes any variables or fucntions that were in scope at the time of creation.

So as you can see, when we return innerFunction from outerFunction, we're not just returning the innerFunction code, we're returning a package of the function and its scope, and this scope that gets returned along with the function, and to which the function keeps access to, is what we call a closure.

Long story short: in JavaScript, a closure is created every time a function is created.

Comming soon...

I will continue expanding on this topic soon, by deepen the discussion on lexical scoping and practical applications like memoization.

Top comments (0)