Closures in JavaScript

Akash ThoriyaAkash Thoriya
1 min read

Expert-Level Explanation

A closure in JavaScript is a function that remembers its outer variables and can access them. In JavaScript, every time a function is created, a closure is created along with it. This allows the function to access variables from its parent scope, even after the parent function has finished executing.

Creative Explanation

Imagine a closure as a backpack that a function takes on a journey. This backpack contains all the resources (variables and functions) that were in scope when the function was declared. The function can use these resources at any point in its journey, even if it's far away from where it started.

Practical Explanation with Code

function outerFunction(outerVariable) {
    return function innerFunction(innerVariable) {
        return outerVariable + innerVariable;
    };
}

const newFunction = outerFunction(3);
console.log(newFunction(5)); // Outputs 8

Real-world Example

Consider a closure like a detective solving a case. The detective (function) gathers clues (variables) from the crime scene (outer scope). Even when they are analysing the case elsewhere, they still have access to these clues.

0
Subscribe to my newsletter

Read articles from Akash Thoriya directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Akash Thoriya
Akash Thoriya

As a senior full-stack developer, I am passionate about creating efficient and scalable web applications that enhance the user experience. My expertise in React, Redux, NodeJS, and Laravel has enabled me to lead cross-functional teams and deliver projects that consistently exceed client expectations.