Skip to Content
Course content
Click on the "Edit" button in the top corner of the screen to edit your slide content.

I want to show you a piece of code that looks perfectly logical at first glance, but behaves in a way that has driven countless developers crazy. Imagine you're building a simple menu where clicking a button tells you which item index was selected.

const buttons = document.querySelectorAll('.menu-item');

for (var i = 0; i < buttons.length; i++) {
  buttons[i].addEventListener('click', function() {
    console.log('You clicked item number: ' + i);
  });
}

You'd expect that clicking the first button prints "0", the second "1", and so on. But here's the problem: no matter which button you click, it always prints the total number of buttons (e.g., "3"). It feels like the code is lying to you.

The shared reference trap

The reason this happens is that the function inside the event listener isn't "saving" the value of i at the moment the listener was created. Instead, it holds a reference to the variable i itself. Because we used var, i is function-scoped (or global), meaning there is only one i for the entire loop.

By the time you actually click a button, the loop has already finished running. The single i variable is now sitting at 3. Every single click handler looks at that same variable and sees the same final number. This is the "aha!" moment where closures become essential.

Creating a snapshot with a closure

To fix this, we need each click handler to have its own private copy of i. We do this by wrapping the listener in another function. This inner function creates a "closure"β€”it captures the value of i at that specific moment in time and holds onto it.

const buttons = document.querySelectorAll('.menu-item');

for (var i = 0; i < buttons.length; i++) {
  (function(index) {
    buttons[i].addEventListener('click', function() {
      console.log('You clicked item number: ' + index);
    });
  })(i); 
}

By using an Immediately Invoked Function Expression (IIFE), I'm passing the current value of i into a new function. The index variable is local to that inner function. Now, each button gets its own unique index variable that doesn't change when the loop continues. I'll be honest: in modern JS, using let in the loop header solves this because let creates a new binding for every iteration, but understanding the closure mechanism is what actually makes you a senior engineer.

The power of private state

Closures aren't just for fixing loop bugs. Their real power is "data hiding." In JavaScript, we don't have a private keyword for variables inside functions. Closures give us a way to mimic this. If you return a function from another function, the returned function still has access to the parent's variables, but the rest of the world does not.

Check this out:

function createScoreTracker() {
  let score = 0; // This variable is "private"

  return {
    increment: function() {
      score++;
      return score;
    },
    decrement: function() {
      score--;
      return score;
    },
    getScore: function() {
      return score;
    }
  };
}

const player1 = createScoreTracker();
console.log(player1.increment()); // 1
console.log(player1.increment()); // 2
console.log(player1.score); // undefined! The variable is protected.

I love this pattern because it prevents other parts of your application from accidentally overwriting score = "pizza"` or some other nonsense. You've created a controlled interface to a piece of state that exists only within that closure.




πŸ“‹ Practical Task

Build a Private-State Digital Stopwatch

Your task is to create a stopwatch factory function called createStopwatch. This function should use closures to protect the stopwatch's internal state so it cannot be modified from the outside.

Requirements:

  • The createStopwatch function should initialize a startTime and a running boolean as private variables.
  • It must return an object with three methods:
    • start(): Sets the startTime to the current time and sets running to true.
    • stop(): Sets running to false.
    • getTime(): Returns the elapsed time in seconds. If the watch isn't running, it should return the time elapsed since the last stop() call.
  • Ensure that the startTime and running variables are not accessible directly from the returned object (e.g., myWatch.startTime should be undefined).
Rating
0 0

There are no comments for now.

to be the first to leave a comment.