Closures and scope are some of the trickier parts of JavaScript. These tools and examples help make them concrete.
Visualisation tools
Run JavaScript code step-by-step and see the call stack and memory state:
Example 1: The classic var in a loop problem
1 | var data = []; |
var is function-scoped, not block-scoped. By the time any of these functions run, the loop has finished and k is 3. All three functions share the same k.
Fix: Use let instead of var in the loop.
Example 2: Block scope with var inside a block
1 | function a() { |
Even though x = 10 exists in the outer scope, the function closes over the x = 5 inside a() because var is hoisted to the function level.
Example 3: Closure capturing a variable, not its value
1 | var a = 100; |
inner closes over abc‘s local a = 10, regardless of any other a variables in other scopes.