Israel
Full-Stack Developer · Posted on Sep 25
JavaScript Closures Explained
A closure is a function that "remembers" variables from its outer scope, even after the outer function has finished executing.
How Closure works? What is a Closure? A closure is a function that "remembers" variables from its outer scope, even after the outer function has finished executing. Simple Mental Model: Think of it as a backpack: when a function is created, it packs up all the variables it needs from its surrounding environment and carries them wherever it goes. Key Concept: Inner functions have access to outer function variables, even after the outer function returns.
js
function createCounter(counter) {
function increament(count = 1) {
return counter + count;
}
function decrement(count = 1) {
return counter > 0 ? counter - count : counter;
}
return {
increament,
decrement,
};
}
const calculate = createCounter(5);
console.log(calculate.increament(2));
console.log(calculate.decrement(1));
const calculate2 = createCounter(0);
console.log(calculate2.decrement());0 comments66 views
Comments
No comments yet — be the first to say something.