How does JavaScript closure work in this example?

function createDisplayFunction(message) {
  return function() {
    displayMessage(message);
  };
}

// processing data array
for (var j = 0; j < dataList.length; j++) {
  var element = dataList[j];
  document.getElementById(element.elementId).onclick = createDisplayFunction(element.text);
}

I’m confused about how the assignment works in the final line. I’ve never encountered this pattern before where a function call result gets assigned to an event handler. Can someone explain what’s happening here? How does the closure preserve the message value for each iteration? I understand basic functions but this syntax is throwing me off. The way the function returns another function and then gets called immediately seems strange to me.

Here’s what’s happening: createDisplayFunction(element.text) runs immediately during each loop iteration and returns a new function. That returned function becomes your onclick handler. When you call createDisplayFunction(element.text), it creates a closure that grabs the specific element.text value from that iteration. The returned function remembers this captured value even after the loop ends. Without this pattern, all your click handlers would reference the same variable and you’d probably see the last element’s text every time. I use this technique all the time for dynamic event binding - it’s super helpful when each handler needs to remember different data from its loop iteration.

createDisplayFunction basically freezes the message value. Each time you call it with element.text, it grabs that specific string and locks it in its own scope. When the click handler runs later, it still has the original message even tho the loop variable moved on. Without this, all your handlers would just share the same variable reference.

Here’s what’s happening: createDisplayFunction is a factory that makes custom functions. When you call createDisplayFunction(element.text), you’re not just running a function - you’re creating a brand new one that gets its own private copy of whatever element.text was at that moment. Picture it like making individual containers, each with a different message inside. The closure keeps that manufactured function working perfectly - even if someone clicks weeks later, it still remembers exactly which message to show. This fixes the classic loop problem where everything would point to the last iteration’s value. Each click handler gets its own personal memory.