Cookie Consent by Free Privacy Policy Generator Aktuallisiere deine Cookie Einstellungen ๐Ÿ“Œ JavaScript Closures Cheatsheet


๐Ÿ“š JavaScript Closures Cheatsheet


๐Ÿ’ก Newskategorie: Programmierung
๐Ÿ”— Quelle: dev.to

1. What is a Closure?

A closure is a function that retains access to its lexical scope even when the function is executed outside that scope.

2. Basic Example

function outerFunction() {
    let outerVariable = 'I am outside!';

    function innerFunction() {
        console.log(outerVariable);
    }

    return innerFunction;
}

const myFunction = outerFunction();
myFunction(); // Output: I am outside!

3. Lexical Scoping

Closures work by capturing variables from their lexical environment.

function makeCounter() {
    let count = 0;

    return function() {
        count++;
        return count;
    }
}

const counter = makeCounter();
console.log(counter()); // 1
console.log(counter()); // 2

4. Immediately Invoked Function Expression (IIFE)

IIFEs create closures to encapsulate variables.

const increment = (function() {
    let counter = 0;
    return function() {
        counter++;
        return counter;
    }
})();

console.log(increment()); // 1
console.log(increment()); // 2

5. Closure with Loop (Common Pitfall)

Using var in a loop can lead to unexpected behavior due to function-level scope.

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

Solution with let:

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

6. Data Privacy

Closures can be used to emulate private variables.

function createSecretHolder(secret) {
    let secretValue = secret;

    return {
        getSecret: function() {
            return secretValue;
        },
        setSecret: function(newSecret) {
            secretValue = newSecret;
        }
    };
}

const holder = createSecretHolder('mySecret');
console.log(holder.getSecret()); // 'mySecret'
holder.setSecret('newSecret');
console.log(holder.getSecret()); // 'newSecret'

7. Partial Application

Closures can be used for partial function application.

function add(a) {
    return function(b) {
        return a + b;
    }
}

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

8. Function Factories

Closures enable function factories.

function multiplier(factor) {
    return function(number) {
        return number * factor;
    }
}

const double = multiplier(2);
console.log(double(5)); // 10

const triple = multiplier(3);
console.log(triple(5)); // 15

9. Module Pattern

The module pattern uses closures to create public and private methods.

const Module = (function() {
    let privateVar = 'I am private';

    function privateMethod() {
        console.log(privateVar);
    }

    return {
        publicMethod: function() {
            privateMethod();
        }
    };
})();

Module.publicMethod(); // 'I am private'

10. Handling Asynchronous Closures

function createCounter() {
    let count = 0;

    return {
        increment: function() {
            count++;
            return count;
        },
        getCount: function() {
            return count;
        }
    };
}

const asyncCounter = createCounter();

setTimeout(() => {
    asyncCounter.increment();
    console.log(asyncCounter.getCount()); // 1
}, 1000);

11. Closures in Event Listeners

function setupButton() {
    let clickCount = 0;

    document.getElementById('myButton').addEventListener('click', function() {
        clickCount++;
        console.log(`Button clicked ${clickCount} times`);
    });
}

setupButton();

12. Common Use Cases

  • Encapsulation: Protecting variables from being accessed or modified outside their intended context.
  • Callbacks: Passing a function as an argument to be executed later.
  • Event Handlers: Managing event-driven programming.
  • Functional Programming: Creating higher-order functions and function factories.

13. Best Practices

  • Minimize the use of closures for better memory management.
  • Be mindful of scope and lifetime of variables.
  • Use const or let instead of var to avoid common pitfalls with closures in loops.

This cheatsheet provides a comprehensive overview of closures in JavaScript, making it ideal for quick revision and reference.

...



๐Ÿ“Œ JavaScript Closures Cheatsheet


๐Ÿ“ˆ 46.24 Punkte

๐Ÿ“Œ Scope, Hoisting and Closures in Javascript


๐Ÿ“ˆ 28.57 Punkte

๐Ÿ“Œ JavaScript Interview Prep: Functions, Closures, Currying


๐Ÿ“ˆ 28.57 Punkte

๐Ÿ“Œ ๐Ÿ“ฆ๐Ÿ”“Closures in JavaScript decoded


๐Ÿ“ˆ 28.57 Punkte

๐Ÿ“Œ Warping realities: JavaScript closures in the Developer's Toolkit.


๐Ÿ“ˆ 28.57 Punkte

๐Ÿ“Œ JavaScript Closures: Demystified


๐Ÿ“ˆ 28.57 Punkte

๐Ÿ“Œ A Practical Introduction to Closures in JavaScript: Part 1


๐Ÿ“ˆ 28.57 Punkte

๐Ÿ“Œ JavaScript Closures in Action: Real-World Applications


๐Ÿ“ˆ 28.57 Punkte

๐Ÿ“Œ How Do Closures Work in JavaScript? Explained with Code Examples


๐Ÿ“ˆ 28.57 Punkte

๐Ÿ“Œ Exploring JavaScript Closures: Practical Examples and Insights


๐Ÿ“ˆ 28.57 Punkte

๐Ÿ“Œ Understanding JavaScript Closures


๐Ÿ“ˆ 28.57 Punkte

๐Ÿ“Œ Understanding Core JavaScript Concepts: Objects, Scopes, and Closures


๐Ÿ“ˆ 28.57 Punkte

๐Ÿ“Œ Understanding Closures in JavaScript


๐Ÿ“ˆ 28.57 Punkte

๐Ÿ“Œ Closures in JavaScript: What They Are and Why They Matter


๐Ÿ“ˆ 28.57 Punkte

๐Ÿ“Œ Understanding Closures in JavaScript


๐Ÿ“ˆ 28.57 Punkte

๐Ÿ“Œ Mastering JavaScript Closures: A Comprehensive Guide


๐Ÿ“ˆ 28.57 Punkte

๐Ÿ“Œ Mastering Closures: Tips and Tricks for Better JavaScript Development


๐Ÿ“ˆ 28.57 Punkte

๐Ÿ“Œ My Visual JavaScript Array Cheatsheet That Went Viral on Linkedin ๐Ÿคฏ๐Ÿ”ฅ


๐Ÿ“ˆ 24.34 Punkte

๐Ÿ“Œ ๐Ÿ“š 34 JavaScript String Methods Cheatsheet


๐Ÿ“ˆ 24.34 Punkte

๐Ÿ“Œ 12 JavaScript Number Methods Cheatsheet


๐Ÿ“ˆ 24.34 Punkte

๐Ÿ“Œ JavaScript Array Methods Cheatsheet


๐Ÿ“ˆ 24.34 Punkte

๐Ÿ“Œ JavaScript Arrays โ€“ JS Array Funktionen erklรคrt (Cheatsheet)


๐Ÿ“ˆ 24.34 Punkte

๐Ÿ“Œ Adobe XD support for Flutter, Architecture Framework, temporary closures with Places API, & more!


๐Ÿ“ˆ 21.9 Punkte

๐Ÿ“Œ Spark blames COVID-19 border closures for slight revenue decline


๐Ÿ“ˆ 21.9 Punkte

๐Ÿ“Œ 7-Eleven Denmark confirms ransomware attack behind store closures


๐Ÿ“ˆ 21.9 Punkte

๐Ÿ“Œ 7-Eleven Denmark confirms ransomware attack behind store closures


๐Ÿ“ˆ 21.9 Punkte

๐Ÿ“Œ 50,000 More Retail Store Closures on the Horizon: Embracing a Data-Driven Approach


๐Ÿ“ˆ 21.9 Punkte

๐Ÿ“Œ Closures: Performance implications


๐Ÿ“ˆ 21.9 Punkte

๐Ÿ“Œ Closures: Lifting the hood


๐Ÿ“ˆ 21.9 Punkte

๐Ÿ“Œ Understanding Closures in Programming


๐Ÿ“ˆ 21.9 Punkte

๐Ÿ“Œ After Public Outcry From Customers, Britain's Biggest Bank HSBC Heads Off Complaints Over Small Business Account Closures


๐Ÿ“ˆ 21.9 Punkte

๐Ÿ“Œ GameStop's poor performance is leading to store closures


๐Ÿ“ˆ 21.9 Punkte

๐Ÿ“Œ Business ID theft soars amid COVID closures


๐Ÿ“ˆ 21.9 Punkte

๐Ÿ“Œ Lexical Scoping vs Closures


๐Ÿ“ˆ 21.9 Punkte

๐Ÿ“Œ Flood of Fake Science Forces Multiple Journal Closures


๐Ÿ“ˆ 21.9 Punkte











matomo