Back to Lessons

JavaScript Closures Explained

April 5, 2026

Closures

Functions retaining access to outer scope variables.

Closure Example

function outer(x) {
    return function inner(y) {
        return x + y;
    };
}

const addFive = outer(5);
console.log(addFive(3)); // 8

// Counter example
function createCounter() {
    let count = 0;
    return function() {
        return ++count;
    };
}

Key Points

  • Inner function accesses outer variables.
  • Used for data privacy, modules.
  • Memory implications (avoid leaks).
  • Common in callbacks, event handlers.