fbpx

Can you explain the concept of closures in JavaScript and provide a practical use case for them?

Certainly. Closures in JavaScript allow functions to remember the lexical scope in which they were defined, even when they are executed outside that scope. A practical use case is creating private variables. For instance:

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

const counter = createCounter();
console.log(counter()); // Output: 1
console.log(counter()); // Output: 2

 

# Dream job to realty