Thursday, December 3, 2015

Making a variable in a loop in javascript evaluate immediatelly

Suppose we have this code:

var td;
for (var i = 1; i < 10; i++) {
  td = document.getElementById('td_' + i);
  if (typeof window.addEventListener === 'function') {
    
    td.addEventListener('click', function() {

      // td is evaluated when the 'click' event occurs and 
      // by then "i" == 10
      console.log(td); 
    
    });

  }
}

console.log(td2) will print "td_10" each time. Why? Because the value of "td" doesn't get evaluated immediately. It's evaluated when the even "click" occurs. And it occurs somewhere after the loop when the variable "i" is equal to 10.

To make "td" evaluate right away, we need to pass it as an argument to a self-invoked function.

var td;
for (var i = 1; i < 10; i++) {
  td = document.getElementById('td_' + i);
  if (typeof window.addEventListener === 'function') {
    
    ///
    // self-invoked function
    (function (td2) {
      
      td.addEventListener('click', function() {
      
        // td2 (being equal to td) is evaluated right away. 
        // When the 'click' event occurs, "i" will have the value of 1 to 9
        console.log(td2); 
      
      });


    })(td);
    ///

  }
}