Mark As Completed Discussion

Step 1: Understand the Problem

The challenge is to create a decrementing counter using closures, which means we need to create a function that returns another function. The inner function should have access to a variable from the outer function, and this variable will serve as our counter.

Step Two

Step 2: Boilerplate Code Analysis

The given boilerplate code provides a starting point:

JAVASCRIPT
1var minus = (function () {
2  // TODO: Initialize a counter variable
3  // TODO: Return a function that decrements the counter and returns the current value
4})();

Here, we see an Immediately Invoked Function Expression (IIFE) that needs to initialize a counter variable and return a function that decrements this counter.

Step 3: Initialize the Counter Variable

First, we need to define a variable inside the IIFE that will act as our counter. This variable will be private, accessible only within the closure.

JAVASCRIPT
1var counter = 999;

Step 4: Create the Inner Function

Next, we need to create an inner function that has access to the counter variable. This function will decrement the counter by 1 each time it is called.

JAVASCRIPT
1return function () {counter -= 1; return counter}

Step 5: Putting It Together

Combining Steps 3 and 4, we obtain the final code for the closure:

JAVASCRIPT
1var minus = (function () {
2  var counter = 999; // Initialize a counter variable
3  return function () {counter -= 1; return counter} // Return a function that decrements the counter
4})();

Step 6: Testing the Code

We can now test our code by calling the minus function multiple times:

JAVASCRIPT
1minus(); // 998
2minus(); // 997
3minus(); // 996

The counter is successfully decremented each time the function is called, demonstrating that our closure is working as intended.

Understanding the Solution

  • The outer function creates a scope where the counter variable is defined, encapsulating it and making it private.
  • The inner function is returned from the outer function and assigned to the variable minus. It maintains access to the counter variable.
  • Each call to minus decrements the counter, and the value is preserved between calls thanks to the closure.
JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment