Understanding JavaScript Closures

Understanding JavaScript Closures

1 min read

Closures are a fundamental concept in JavaScript that allow functions to access variables from their outer scope. This article explains closures, their practical uses, and common pitfalls.

What Are Closures?

A closure is the combination of a function bundled together with references to its surrounding state.

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

const closureExample = outerFunction("I am from outerFunction");

// Calling the inner function with the closure
closureExample("I am from innerFunction");

Articles similaires

JavaScript Math is a Lie

JavaScript Math is a Lie

A hilariously painful journey through floating point math in JavaScript. Yes, 0.1 + 0.2 ≠ 0.3.

Programming
1 min read
A Functions Existential Crisis

A Functions Existential Crisis

A lighthearted guide to recursion—aka that thing you call within itself until it forgets why it started.

Programming
1 min read