✅ Logical Operators in JavaScript – Complete Guide with Real Examples

In JavaScript, a closure is created when a function "remembers" the variables from its outer scope even after the outer function has finished executing. This concept allows functions to access variables from an enclosing scope or function — even after that outer function has returned.
Closures are a powerful feature in JavaScript that enable data encapsulation, callback handling, and the creation of private variables.
function outerFunction() {
let outerVariable = "I am from outer scope!";
function innerFunction() {
console.log(outerVariable); // Accessing variable from outer scope
}
return innerFunction;
}
const closureFunc = outerFunction();
closureFunc(); // Output: I am from outer scope!
outerFunction
defines a variable outerVariable
.innerFunction
is declared inside outerFunction
and uses that variable.outerFunction()
has finished executing, innerFunction()
can still access outerVariable
.Closures are used to:
setTimeout
).
function createCounter() {
let count = 0;
return function() {
count++;
console.log(count);
};
}
const counter1 = createCounter();
counter1(); // 1
counter1(); // 2
const counter2 = createCounter();
counter2(); // 1
π Each counter
maintains its own separate copy of count
due to closures.
Closures in JavaScript may seem tricky at first, but they are essential for writing modular, maintainable, and efficient code. Understanding closures will help you master more advanced concepts like callbacks, currying, and function factories.
π±️ Explore this powerful concept in your code today and see the magic of closures in action!
Comments
Post a Comment