rudolph schmitz rudolph schmitz - 2 years ago 228
Javascript Question

JSHint warning about closures inside loops using outer variables

My code does work but I don't want the jshint errors anymore:


Functions declared within loop referencing an outer scoped variable may lead to confusing semantics



  1. I've tried using let from ES6 to get around the error because I thought that would solve the problem. I configured my gruntfile to use ES6 as well.

  2. I tried using two loops, the outer loop with variable 'i' and the inner loop with variable 'j'



Neither worked.

Full code provided here: https://jsfiddle.net/rwschmitz/zz7ot3uu/

var hobbies = document.getElementsByClassName("hobbies");
var active = false;

// For mouse input

for (var i = 0; i < 5; i++) {
hobbies[i].onmouseover = function() {
hobbies[0].classList.add('hobbies-slide-left');
hobbies[1].classList.add('hobbies-slide-right');
hobbies[2].classList.add('hobbies-slide-left');
hobbies[3].classList.add('hobbies-slide-right');
hobbies[4].classList.add('hobbies-slide-left');
};
}

// For click input

for (var i = 0; i < 5; i++) {
hobbies[i].onclick = function() {
hobbies[0].classList.add('hobbies-slide-left');
hobbies[1].classList.add('hobbies-slide-right');
hobbies[2].classList.add('hobbies-slide-left');
hobbies[3].classList.add('hobbies-slide-right');
hobbies[4].classList.add('hobbies-slide-left');
};
}

Answer Source

You could change your loops to something like this, using Array#map() and Array#forEach():

var hobbies = Array.from(document.getElementsByClassName('hobbies'));
var classes = ['hobbies-slide-left', 'hobbies-slide-right'];

function addHobbyClass (hobby, index) {
  hobby.classList.add(this[index % this.length]);
}

function hobbyEventListener () {
  hobbies.forEach(addHobbyClass, classes);
}

hobbies.map(function (hobby) {
  hobby.addEventListener('mouseover', hobbyEventListener);
  hobby.addEventListener('click', hobbyEventListener);
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download