Back

Closure on the Concept of JavaScript Closures

07 Jan 2025

main image for Closure on the Concept of JavaScript Closures

I was recently talking with a senior developer who was asking me JavaScript questions to gauge my knowledge. Before that conversation, I felt confident. After it, I felt deflated. It became clear that I still had work to do.

My goal is to become comfortable with the areas where I fell short. To that end, I want to bring clarity to one of the most important and confusing JavaScript concepts: closures.

Understanding Closures

Closures are tricky, but they become easier to understand when broken down. A closure happens when a function can remember and access variables from its outer scope, even after that outer scope has finished executing.

Key takeaway: Closures enable functions to remember and access variables from their surrounding context, even after that context has finished executing.

Example of a Closure

Here’s a simple example to illustrate how closures work. Create an HTML file, link a script.js file, and paste the following code. Refer back to this block throughout the article.

function outerFunction(outerVariable) {
  return function innerFunction(innerVariable) {
    console.log(`Outer Variable: ${outerVariable}`);
    console.log(`Inner Variable: ${innerVariable}`);
  };
}

const closureFunc = outerFunction('outside');
closureFunc('inside');

Explanation:

Closure concept illustration

Breaking Down the Code

Let’s reference the code block above and walk through it step by step.

Step 1: Defining the Outer Function

outerFunction is defined with one parameter: outerVariable.

Step 2: Returning the Inner Function

Instead of executing innerFunction, outerFunction returns it. The returned function retains access to outerVariable.

Step 3: Parameters in Scope

outerVariable belongs to outerFunction, but remains accessible inside innerFunction due to the closure.

Step 4: Logging Inside the Inner Function

innerFunction logs both outerVariable and innerVariable, demonstrating how closures preserve access to outer scope variables.

How closures work diagram

How the Function Calls Work

1. Calling outerFunction

const closureFunc = outerFunction('outside');

2. Calling innerFunction via closureFunc

closureFunc('inside');

In short: closureFunc is the returned innerFunction. It remembers the argument passed to outerFunction and accepts a new argument for itself.

Thinking about closures

Common Misunderstandings

Why doesn’t closureFunc('inside') invoke outerFunction again?

Why Closures Matter

Final Thoughts

Closures are a foundational JavaScript concept. While they can be confusing at first, understanding them deepens your grasp of functions and scope. With practice, closures become a natural and powerful part of your JavaScript toolkit.