Home Web Front-end JS Tutorial The Magic of JavaScript Closures: A Clear and Easy Guide

The Magic of JavaScript Closures: A Clear and Easy Guide

Jan 09, 2025 am 07:02 AM

What Are Closures in JavaScript?

Think of a closure like a backpack you carry with you after a class. Inside the backpack, you have all the notes and materials you learned during the class. Even after the class ends, you still have access to everything in your backpack whenever you need it. Similarly, a closure allows a function to keep access to the variables and parameters from its outer scope, even after that outer function has finished running and those variables are no longer accesssible outside of that function.

The explanation above is a typical way to describe closures, but is it beginner-friendly for someone new to JavaScript? Not really. I found it quite confusing when I first encountered it too. That's why I've written this article to make closures as simple as possible for anyone to understand. We'll begin by covering the basics before diving deeper into the topic.

Understanding Scope in JavaScript

To understand what closures is, we have to take a brief look at scope in JavaScript. Scope refers to the accessibility of variables and functions in different parts of our code. It determines where we can access certain variables or functions within our program.

There are two primary types of scope: global scope and local scope. Variables declared in the global scope exist outside of any function or block, making them accessible throughout the entire code. In contrast, variables declared in the local scope, such as within a function or block, are only accessible within that specific function or block. The code below illustrates this explanation.

// GLOBAL SCOPE
let myName = "John Doe";

function globalScope() {
  console.log(myName);
}
globalScope(); //Output John Doe
console.log(myName); // Accessible here as well

// LOCAL SCOPE
function localScope() {
  let age = 30;
  console.log(age);
}
localScope(); //Output 30
console.log(age); //Output age is not defined (Not Accessible)
Copy after login
Copy after login
Copy after login

However, JavaScript uses a concept known as Lexical Scoping, which is crucial to understanding how closures work. Lexical Scoping means that the accessibility of variables is determined by the structure of our code at the time it is written. In simple terms, it’s like saying, "If a variable is declared inside a function, only that function and anything within it can access that variable."{https://javascript.info/closure}.

Lexical Scoping and Execution Context

To understand this more clearly, let's look at how JavaScript works behind the scenes. JavaScript uses something called an Execution Context, which is like a container that holds the code being run. It keeps track of variables, functions, and what part of the code is currently running. When a script starts, the Global Execution Context (GEC) is created. It’s important to note that there is only one Global Execution Context in a program.

The Magic of JavaScript Closures: A Clear and Easy Guide
The diagram above represents the Global Execution Context when our program begins. It consists of two phases: the Creation (or Memory) Phase and the Execution (or Code) Phase. In the Creation Phase, variables and functions are stored in memory—variables are initialized as undefined, and functions are fully stored. In the Execution Phase, JavaScript runs the code line by line, assigning values to variables and executing functions.

Now that we understand how JavaScript handles the execution context and lexical scoping, we can see how this directly ties into closures.

How Closures Work: An Example

A closure in JavaScript is created when an inner function retains access to the variables in its outer function's scope, even after the outer function has finished execution. This is possible because the inner function preserves the lexical environment it was defined in, allowing it to "remember" and use the variables from its outer scope.

// GLOBAL SCOPE
let myName = "John Doe";

function globalScope() {
  console.log(myName);
}
globalScope(); //Output John Doe
console.log(myName); // Accessible here as well

// LOCAL SCOPE
function localScope() {
  let age = 30;
  console.log(age);
}
localScope(); //Output 30
console.log(age); //Output age is not defined (Not Accessible)
Copy after login
Copy after login
Copy after login

Here is a guide on how the above code works. Whenever we call a function, the JavaScript engine creates a function execution context (FEC) specific to that function, which is created within the Global Execution Context (GEC). Unlike the GEC, there can be multiple FECs in a program. Each FEC goes through its own creation and execution phases and has its own variable and lexical environments. The lexical environment enables the function to access variables from its outer scope.

When outerFunction is called, a new FEC is created, Inside outerFunction, we define innerFunction, which has access to outerVariable due to lexical scoping. After outerFunction returns, the execution context of outerFunction is removed from the call stack, but the innerFunction retains access to outerVariable because of the closure. So, when we later call closureExample(), it can still log outerVariable even though the outerFunction has completed.

Real-World Applications of Closures

Let’s examine the following example:

Let’s look at the example below:

function outerFunction() {
    let outerVariable = 'I am John Doe';

    return function innerFunction() {
        console.log(outerVariable);
    };
}

const closureExample = outerFunction();
closureExample();  // Outputs: "I am John Doe"
Copy after login

What do you think the output of this code will be? Many of you might have guessed 5, but is that really the correct output? Actually, no, and here’s why. The function y() is referencing the variable a, not its initial value. When z() is called, it logs the current value of a, which is 50, due to the update made before returning the inner function. Let's explore another example:

function x(){
      let a = 5
     function y(){
         console.log(a)
      }
      a = 50
      return y;
    }
    let z = x();
    console.log(z)
    z();
Copy after login

code demonstrates the power of closures. Even in the innermost function, z(), it can still access variables from its parent scopes. If we inspect the browser and check the Sources tab, we can see that closures have formed on both x and y, which allows z() to access a and b from its parent contexts.

The Magic of JavaScript Closures: A Clear and Easy Guide

Advantages of Using Closures

Closures offer several advantages in JavaScript, especially when writing more flexible, modular, and maintainable code. Below are some of the key advantages:

1. Callback Functions: Closures are very powerful when dealing with asynchronous programming, such as callbacks, event listeners, and promises. They allow the callback function to maintain access to variables from the outer function even after the outer function has completed.

// GLOBAL SCOPE
let myName = "John Doe";

function globalScope() {
  console.log(myName);
}
globalScope(); //Output John Doe
console.log(myName); // Accessible here as well

// LOCAL SCOPE
function localScope() {
  let age = 30;
  console.log(age);
}
localScope(); //Output 30
console.log(age); //Output age is not defined (Not Accessible)
Copy after login
Copy after login
Copy after login

2. Modularity and Maintainability: Closures encourage modularity by allowing developers to write smaller, reusable chunks of code. Since closures can preserve variables between function calls, they reduce the need for repetitive logic and improve maintainability.

3. Avoiding Global Variables: Closures help reduce the need for global variables, thus avoiding potential naming conflicts and keeping the global namespace clean. By using closures, you can store data in function scope rather than globally.

Conclusion

Closures are a powerful concept in JavaScript that extend the capabilities of functions by allowing them to remember and access variables from their outer scope, even after the function has executed. This feature plays a significant role in creating more modular, flexible, and efficient code, particularly when handling asynchronous tasks, callbacks, and event listeners. While closures might seem complex at first, mastering them will enable you to write more sophisticated and optimized JavaScript. As you continue to practice, you’ll discover how closures can help in writing cleaner, more maintainable applications. Keep experimenting, and soon closures will become a natural part of your JavaScript toolbox.

The above is the detailed content of The Magic of JavaScript Closures: A Clear and Easy Guide. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1243
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

See all articles