0

I’m getting a JSHint/JSLint error on my code below.

Functions declared within loops referencing an outer scoped variable may lead to confusing semantics. ($, currentVal)

This is directed at the $options.each loop where I’m pushing to currentVal.

Any thoughts on how to solve this?

$(".option input[type=radio]").change(function() {
  reload_filterstring(this);
});

$(".option input[type=checkbox]").change(function() {
  reload_filterstring(this);
});

function reload_filterstring(that) {
  var finalFilterQuery = {};

  var currentEl = "";

  (filterType = $this.attr("data-filter-type")),
  ($options = $this.find("ul.options input")),
  (query = $this.find('input[name="query"]')),
  (finalQuery = $('input[name="finalQuery"]')),
  (filterData = []),
  (filterQuery = null);

//  console.log(filterName);

currentVal = [];

$options.each(function() {
  if ($(this).prop("checked") == true) {
    currentVal.push($(this).attr("id"));
  }
});

finalFilterQuery[filterName] = currentVal.join("|");
  }

  // console.log(finalFilterQuery);
  var str = "";
  for (var key in finalFilterQuery) {
if (finalFilterQuery.hasOwnProperty(key)) {
  if (str != "") {
    str += ",";
  }
  str += key + "=" + finalFilterQuery[key];
}
  }
  console.log(str);
}

https://codepen.io/anon/pen/drMRem?editors=1111

John the Painter
  • 2,495
  • 8
  • 59
  • 101

1 Answers1

-1

I ran with codepen.io JS Analyse and the result was: Don't make functions within a loop. with a link to this JS Hint - don't make functions within a loop. You should move the function out instead of placing it inside a loop, but if you still insist on having a function inside the loop, you can narrow down the scope of currentVal inside the function like below:

$options.each(function($currentVal) {
  return function() {
    if ($(this).prop("checked") == true) {
      $currentVal.push($(this).attr("id"));
    };
  }(currentVal));
Kei Huynh
  • 29
  • 5