Search code examples
javascriptvariablesecmascript-6scopeecmascript-5

Push Functions to an array, Convert let to var


Is it possible to push functions to an array using var instead of let. The code I'm looking at is:

function slideRightLoop() {
    let work = [];

    for (var n = 1; n < 5; n++) {
        let next = (n + 1 < 5) ? n + 1 : 1;
        let el = document.querySelector(".position_" + n)[0];
        var change = function change () {
            el.classList.add("position" + next);
            el.classList.remove("position_" + n);
        }
        work.push(change);
    }

    work.forEach(function (n) { 
      return n();
    });
}

Solution

  • You can just put it into https://babeljs.io/repl/ and see what is converted to. The simplest way is to make the loop body a function which accepts all loop variables as arguments:

    function slideRightLoop(n, work) {
      var next = (n + 1 < 5) ? n + 1 : 1;
      var el = document.querySelector(`.position_${n}`);
      var change = function change () {
          el.classList.add(`position_${next}`);
          el.classList.remove(`position_${n}`);
      }
      work.push(change);
    }
    
    function slideRight() {
        var work = [];
    
        for (var n = 1; n < 5; n++) {
          slideRightLoop(n, work);
        }
    
        work.forEach(function (n) { 
          return n();
        });
    }