JSlint: unexpected 'for' [duplicate]

Solution 1:

JSLint suggests you use other loops such as forEach. http://www.jslint.com/help.html#for

You can just select the tolerate "for statement" option at the bottom if this bothers you but the code looks fine.

Solution 2:

Here's the best explanation I could find for you,

Recently I decided I don't need to use for anymore. I'm done with for loops. for loops were invented, they came out of Fortran. They were intended to be a way of working through an array, but in ES5 we added forEach() and map() and all the others, I was like 'Yeah, that's the way to do it'. The for syntax is so weird anyway with the thing with the three statements in it.

Crockford further goes on to talk about being done with loop constructs altogether in ES6, and using just functional constructs instead.

You can choose to ignore it - just pass the option to JSLint to tolerate for.


However, let's say you decided to do away with the for loop you have. You could with every(). It would be something like (not tested):

intoFunction: function () {
    var radios, found; 
    radios = document.getElementsByName("cb");
    found = Array.prototype.slice.call(radios).every(function(radio) {
        if (radio.checked) { 
            alert(radio.value); 
            return false; 
        }
        return true; 
    }); 

    if (found) {
        alert("Please Select Radio");
    }
}

It is honestly arguable in my opinion if this is easier to understand that a for loop. Honestly it depends upon your own personal / project's coding standards.


Updated with a working snippet demonstrating every() to accomplish this.

function into() {
  var radios, found;
  radios = document.getElementsByName("cb");
  found = Array.prototype.slice.call(radios).every(function(radio) {
    if (radio.checked) {
      alert(radio.value);
      return false;
    }
    return true;
  });

  if (found) {
    alert("Please Select Radio");
  }
}

jQuery("[name='cb']").on("click", into);
jQuery("button").on("click", function() {
  jQuery("[name='cb']").prop("checked", false);
  into();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
  <label>
    <input type="radio" name="cb" value="M">Male</label>
</p>
<p>
  <label>
    <input type="radio" name="cb" value="F">Female</label>
</p>
<p>
  <label>
    <input type="radio" name="cb" value="I">I don't know</label>
</p>
<p>
  <label>
    <input type="radio" name="cb" value="B">Both</label>
</p>
<p>
  <button>Clear Radios</button>