𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗖𝗹𝗼𝘀𝘂𝗿𝗲𝘀 𝗘𝘅𝗽𝗹𝗮𝗶𝗻𝗲𝗱
You use closures every day in JavaScript. You likely use them in React hooks, event listeners, and Node.js callbacks. Many developers struggle with the theory, but the concept is simple once you see the pattern.
To understand closures, you must understand lexical scope.
Lexical scope means a function can access variables from its own scope and any outer scope where it was defined. It depends on where you write the code, not where you call it.
A closure is a function that remembers variables from its original scope even after that scope finishes running.
Think of a function as carrying a backpack. When the function is created, it packs every variable it needs from its environment into that backpack. The function takes that backpack everywhere it goes.
Here is how closures work in practice:
Private Variables: You can hide data from the outside world. In a bank account example, a balance variable stays private. You can only change it through specific methods like deposit or withdraw. This prevents direct access to sensitive data.
Function Factories: You can create functions that produce other functions. A multiplier factory can create a double function or a triple function. Each new function keeps its own specific multiplier in its backpack.
Event Listeners: When you attach a click event to a button, the handler remembers the data from the setup function. Even after the setup function finishes, the listener holds onto that data.
React Hooks: Every time you use useState or useEffect, you use closures. A common bug in React happens when a closure captures an old value of state. This is called a stale closure.
Watch out for memory usage. Because a closure holds a live reference to variables, the engine cannot clean them up through garbage collection while the closure exists. Avoid holding massive objects in a closure if you do not need them for a long time.
Summary:
- Lexical scope defines access.
- Closures make that access persistent.
- A function carries its environment in a backpack.
- Use let instead of var in loops to avoid scoping bugs.
Source: https://dev.to/digitalunicon/javascript-closures-explained-with-examples-339f