Skip to main content

Command Palette

Search for a command to run...

Understanding JavaScript Closures

Published
•1 min read•View as Markdown
Understanding JavaScript Closures
O
I'm a Product Engineer at IDnow based in Berlin, originally from Romania and raised in sunny Spain. I build accessible, user-focused web applications with React, TypeScript, and modern frontend technologies. Beyond coding, I enjoy sharing knowledge through technical documentation, Communities of Practice (CoPs), and mentoring. I'm passionate about frontend architecture, web standards, accessibility (A11y), and writing clean, maintainable code.

Grasping the concept of closures in JavaScript took some time, but I've come to understand it well.

What is a Closure?

A closure is a function bundled with its lexical environment, meaning it retains access to its scope even when the function is executed outside that scope.

Why are Closures Important?

Closures allow inner functions to access variables from an outer function's scope. This is powerful in JavaScript, where functions can be:

  • Assigned to variables

  • Passed as parameters to other functions

  • Returned from other functions

How Do Closures Work?

Closures can be tricky, especially when a function returns another function. In such cases, the inner function "remembers" its lexical scope, including any variables it accessed when it was created.

Here's a simple example to illustrate the fundamentals of closures:

function outerFunction() {
  let a = 1;
  return function innerFunction() {
    console.log(a);
  };
}

const myClosure = outerFunction();
myClosure(); // Outputs: 1

Even though outerFunction has finished executing, innerFunction retains access to the variable a from its lexical scope.

Closures are an essential concept in JavaScript, despite the potentially confusing terminology. Understanding them is key to mastering the language.