Closure - jellyfish-tom/TIL GitHub Wiki

[SOURCES]

Closure is when a function is able to remember and access its lexical scope even when that function is executing outside its lexical scope.

Closures are inner functions inside of an outer function. They have their own local scope and has access to outer function’s scope, parameters (but NOT arguments object), and they also have access to global variables.

Closures maintain access to the environment in which they were created, even though that environment execution is long gone.

This is how Closures work.

  1. After its outer function has been executed and has returned a value, closures can still get executed/called.
  2. Closures store references to the outer function’s variable, hence, we will always have access to the updated values of outer function’s variables.
  3. Since we have access to the updated values of outer function’s variables. We will have issue/bugs when a variable changes via for loop, but this can be fixed by using IIFE - Immediately Invoked Function Expression.