Closures in JavaScript

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.