1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function createCounter() {
let count = 0; // This is the variable that will be "closed over"
return function() {
count++; // This inner function has access to the 'count' variable
console.log(count);
return count;
};
}
const counter = createCounter();
counter(); // Outputs: 1
counter(); // Outputs: 2
counter(); // Outputs: 3
// Creating a new counter
const counter2 = createCounter();
counter2(); // Outputs: 1
counter2(); // Outputs: 2
// The original counter is unaffected
counter(); // Outputs: 4No Output
Run the code to generate an output.