Upgrade to Pro — share decks privately, control downloads, hide ads and more …

JavaScript Closure

JavaScript Closure

This deck summarises the concept of closure in JavaScript.

Austin Asoluka

May 03, 2024
Tweet

Other Decks in Programming

Transcript

  1. @asoluka_tee JavaScript Closure 1. Function sally is invoked (pushed into

    the call stack), it creates a scope (the entire pink area labeled sally which is depicted above). The age variable and joe function lives in Sally's lexical environment/scope. 2. Function joe makes use of the age variable which belongs to sally function and because of this, a closure is created and the age variable is placed in the closure.
  2. @asoluka_tee 3. The joe function is invoked, placed in the

    call stack (notice that by this time, sally is no longer in the call stack because it has finished executing so its environment has been cleared up). 4. During the execution of the joe function, joe makes reference to variable age but then which variable age? Ah yes! the one stored in the closure (notice that the closure created at step 2 lives in joe’s execution environment hence we have access to it). Tip: Closure is created when a child function makes use of (or references) a variable within its parent/lexical scope.