๐Ÿš€ Understanding Closures in JavaScript ๐Ÿ”ฅ

AnjaliAnjali
2 min read

Closures are an important concept in JavaScript that help functions remember the variables from their parent function, even after the parent function has finished running. ๐Ÿง โœจ

๐Ÿค” What is a Closure?

A closure happens when a function is created inside another function and keeps access to the outer function's variables. ๐Ÿ”„

๐Ÿ“ Example:

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

const newFunction = outerFunction("Hello");
newFunction("World");

๐Ÿ–ฅ๏ธ Output:

Outer: Hello, Inner: World

โœ… Even though outerFunction has finished running, innerFunction still remembers outerVariable.

๐ŸŽฏ Why Use Closures?

1๏ธโƒฃ Data Privacy ๐Ÿ”’

Closures help keep variables private:

function counter() {
    let count = 0;
    return function () {
        count++;
        console.log(count);
    };
}

const myCounter = counter();
myCounter(); // 1๏ธโƒฃ
myCounter(); // 2๏ธโƒฃ

๐Ÿ”น count cannot be accessed directly from outside.

2๏ธโƒฃ Remembering Values ๐Ÿง 

Closures help functions remember values:

function multiply(x) {
    return function(y) {
        return x * y;
    };
}

const double = multiply(2);
console.log(double(5)); // ๐Ÿ”Ÿ

โœ… The function double remembers x = 2.

โš ๏ธ A Common Mistake ๐Ÿšจ

Using var inside a loop can cause unexpected results:

for (var i = 0; i < 3; i++) {
    setTimeout(function() {
        console.log(i);
    }, 1000);
}

โณ Output (after 1 second):

3
3
3

โŒ Why? Because var is function-scoped and all callbacks refer to the same i.

โœ… Fix: Use let instead of var to create a new scope for each loop:

for (let i = 0; i < 3; i++) {
    setTimeout(function() {
        console.log(i);
    }, 1000);
}

โœ… Correct Output:

0
1
2

๐ŸŽ‰ Conclusion

Closures are powerful! ๐Ÿ’ก They help with: โœ… Keeping variables private ๐Ÿ”’ โœ… Remembering values ๐Ÿง  โœ… Handling loops correctly ๐Ÿ”„

Mastering closures will make you a better JavaScript developer! ๐Ÿš€

10
Subscribe to my newsletter

Read articles from Anjali directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Anjali
Anjali