Translation: I Never Understood JavaScript Closures

https://medium.com/dailyjs/i-never-understood-javascript-closures-
I read “I never understood Javascript closures” and translated and organized my notes on it.


Execution context: the environment/scope where the current code is evaluated. A program starts in the global execution context. Some variables are declared within that context. These are called global variables.

What happens when a program calls a function?

  1. JavaScript creates a new execution context: a local execution context.
  2. This local execution context has its own set of variables, scoped only to that context.
  3. The new execution context is pushed onto the execution stack. Think of the execution stack as a mechanism for tracking where the program is during execution.

When does a function end? When it reaches a return statement or the closing brace. The following then happens:

  1. The local execution context is popped off the execution stack.
  2. The function sends its return value back to the calling context. The calling context is the execution context that called the function: either the global execution context or another local one. It must handle the return value at that point. A return value can be an object, array, function—really anything. If there is no return statement, undefined is returned.
  3. The local execution context is destroyed, and all variables declared within it are erased. They are no longer available. That’s why they’re called local variables.

A quick recap

Function ends → execution context pops → return value moves to calling context → return value is handled → local execution context is destroyed → variables are removed

a = 3 // Declare a new variable in the global execution context. Assign a number to a.
addTwo(x) { // The code inside isn't executed; it's only stored in a variable for later use.
ret = x + 2 // New variables are declared in the local execution context. The argument assigns a number to x. Declare ret in the local execution context; its value is initially undefined.
return ret // Return the variable's contents. Look it up locally. The function returns a number and ends.
 } // Destroy the local execution context. x and ret no longer exist.
b = addTwo(a) // Switch execution contexts. Create a new local execution context and push it onto the call stack.
console.log(b)

A new example

1: let val1 = 2
2: function multiplyThis(n) {
3:   let ret = n * val1
4:   return ret
5: }
6: let multiplied = multiplyThis(6)
7: console.log('example of scope:', multiplied)

The difference here is that there are variables in both the local and global execution contexts.

If a variable can’t be found in the local execution context, look in the calling context.

If it isn’t there, look in that context’s calling context. Repeat until reaching the global execution context.

A function that returns a function

 1: let val = 7 // Declare a global variable and assign a number.
 2: function createAdder() { // Declare a variable and assign the definition. Only store the function.
 3:   function addNumbers(a, b) {
 4:     let ret = a + b
 5:     return ret
 6:   }
 7:   return addNumbers
 8: }
 9: let adder = createAdder() // Declare a global variable, temporarily undefined. Query global memory, find createAdder, and call it.
10: let sum = adder(val, 8)
11: console.log('example of function returning a function: ', sum)

When createAdder is called:

The call creates a new local execution context.

Local variables are created in the new execution context.

The engine adds the new context to the call stack.

Line 3: create a variable in the local execution context. addNumbers exists only in this context.

Store the function definition in the local variable.

Return addNumbers.

Destroy the local execution context. The addNumbers variable no longer exists, but the function definition remains. It is assigned to adder.

On line 10, define sum in the global execution context. Its temporary value is undefined.

Execute the function defined in the variable. Find adder in the global execution context.

Execute adder.

Recap

  1. Function definitions can be stored in variables, and the program doesn’t look inside the definition until the function is called.
  2. Every function call temporarily creates a local execution context. It disappears when the function finishes. A function finishes when it reaches return or the closing brace.

The final example (I think I’m starting to get it…)

 1: function createCounter() { // Create a global variable, createCounter, and assign the function definition.
 2:   let counter = 0 // Declare a local variable and assign 0 to counter.
 3:   const myFunction = function() { // Declare a local variable. Create a closure as part of the function definition.
 4:     counter = counter + 1
 5:     return counter
 6:   }
 7:   return myFunction .// Return the variable's contents.
 8: }
 9: const increment = createCounter() // Call createCounter and assign the returned value to the variable.
10: const c1 = increment()
11: const c2 = increment()
12: const c3 = increment()
13: console.log('example increment', c1, c2, c3)

Based on what we’ve covered so far, counter on line 4 should return undefined, and

become 0, giving c1, c2, and c3 the values 1, 1, and 1.

But that’s before we understand closures.


9: Call createCounter. Assign its return value to increment.

2: Declare a new local variable called counter. Assign 0.

3–6: Declare a new local variable called myFunction.

7: Return the contents of myFunction. The local execution context is deleted and no longer exists. Return the function definition with its closure: a backpack containing counter.

9: Assign the value to increment in the calling context, which is the global execution context. The variable now contains a function definition.

10: Look up the variable. Find increment and call it. It contains the previously returned function definition, along with a backpack of variables.

Create a new execution context. No parameters. Execute the function.

4: We need to find counter. (The key is that it isn’t undefined.) Before looking in the local or global execution context, let’s check the backpack. Check the closure.

And so, counter

The key: when a function is declared, it includes both its definition and its closure.

A closure is the collection of all variables that were in scope when the function was created.

Does every function have a closure? Yes.

Functions created in global scope create closures. But these functions, in global scope

Sometimes closures appear without us noticing. This is called partial application.

let c = 4;
function addX(x) {
	return function (n) {
		return n + x;
	};
}
const addThree = addX(3);
let d = addThree(c);
console.log("example partial application", d);

addX declares a general-purpose addition function that takes one parameter, x, and returns another function.

The returned function also takes one parameter and adds it to the variable.

The variable is part of the closure. When addThree is declared in the local context, it is assigned the function definition and closure. The closure contains the variable.

Now, when it’s called and executed, it can access the variable in addThree’s closure and the variable passed as an argument, and return their sum.

The console prints 7.


Wrapping up.

I remember closures through the backpack analogy. When a function is created and passed to or returned from another function, it carries a backpack. That backpack holds all the variables that were there when the function was declared. SpongeBob meme