To better understand, it is important to note that each time the function is called recursively, a unique cool
variable is created. This variable is not shared across all function executions, but rather each call generates its own instance of the variable. When the += 1
operation is performed, only that specific variable is modified while previous instances remain unchanged.
In the given example, the initial call establishes the variable with a value of 0 (as passed to it), which increments to 1 and remains constant thereafter.
Subsequent recursive calls create new instances of the cool
variable, each starting with a value of 1, incrementing to 2, and then remaining static.
Each iteration of cool
exists within its own "box", illustrating a series of nested contexts during execution.
For simplicity, the function is limited to run until 3 for easier tracking:
function wow(cool) {
if(cool === 3) return;
cool += 1;
console.log(cool);
wow(cool);
console.log(cool);
}
wow(0);
The following outlines the sequential execution contexts, with each box representing a distinct context. Execution proceeds from top to bottom:
+----------------------------------------------+
| cool = 0 |
| cool += 1 // = 1 |
| console.log(cool) // 1 |
| +--------------------------------------+ |
| | cool = 1 | |
| | cool += 1 // = 2 | |
| | console.log(cool) // 2 | |
| | +------------------------------+ | |
| | | cool = 2 | | |
| | | cool += 1 // = 3 | | |
| | | console.log(cool) // 3 | | |
| | | +-----------------------+ | | |
| | | | cool = 3 | | | |
| | | | if (cool == 3) return | | | |
| | | +-----------------------+ | | |
| | | console.log(cool) // 3 | | |
| | +------------------------------+ | |
| | console.log(cool) // 2 | |
| +--------------------------------------+ |
| console.log(cool) // 1 |
+----------------------------------------------+
It's evident that each instance of cool
exists within its own context, independent from variables in deeper nested contexts.