Understanding JavaScript Closures in For Loops

How do you pass a variable into a function inside a loop?
It always ends up taking the last value!
What gives?

Let’s suppose you’re lucky enough to work for a company that gives annual cost-of-living pay increases. Let’s also suppose the corporate payroll system is written in JavaScript. (Why not? everything seems to be JavaScript these days)

And, because we’re big enterprise, our system is rife with inefficiency and we’ve over-engineered everything. Below is what the payroll function looks like. (This is a totally contrived example… so you’ll have to practice suspension of disbelief rather than ask why it’s designed so poorly)

// Queue jobs to assign employee pay increases
function queueEmployeeRaises(employees, jobQueue, database, multiplier) {
  for (var i = 0; i < employees.length; i++) {
    var employee = employees[i];
    jobQueue.push(function() {
      if (employee.title == 'CEO') {
        employee.salary = employee.salary * Math.max(1.20, multiplier);
      }
      else {
        employee.salary = employee.salary * Math.min(multiplier, 1.02);
      }
      database.save(employee);
    });
  }
}

Continue reading “Understanding JavaScript Closures in For Loops”

Understanding JavaScript Closures in For Loops