0

I'm using a somewhat unconventional for loop that works well for what I'm doing as paraphrased below (not bothering to show variable declarations):

if (arr && arr.length > 0) {
    for (i = arr.length; i--; i) {
        element = arr.pop();
        //rest of code
    }
}

Closure compiler is giving me a warning of: "WARNING - Suspicious code. This code lacks side effects, is there a bug?" Pointing specifically to the last "i" in the for loop parens.

If I remove the i, jslint throws a warning, if I leave it, closure throws a warning. There are three of these loops in total, is there a "closure friendly" way to do this?

Shane
  • 4,921
  • 5
  • 37
  • 53

4 Answers4

3

How 'bout the normal way?

if (arr && arr.length > 0) {
    for (i = arr.length; i > 0; --i) {
        element = arr.pop();
        //rest of code
    }
}

Putting the decrement in the test is just not the normal way to write a for loop.

Or even more normal:

if (arr && arr.length > 0) {
    for (i = arr.length - 1; i >= 0; --i) {
        element = arr.pop();
        //rest of code
    }
}

...but as you're not using i, it doesn't matter much.

Or you could use a while:

if (arr && arr.length > 0) {
    i = arr.length;
    while (i--) {
        element = arr.pop();
        //rest of code
    }
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

For future readers, if you're reducing an array's length, don't use a for loop, use a while:

if (arr) {
    while (arr.length) {
        element = arr.pop();
        ...
    }
}
Walf
  • 8,535
  • 2
  • 44
  • 59
0

Yeah--something like this should do the trick:

for (i = arr.length; i > 0; i--) {
Elliot Bonneville
  • 51,872
  • 23
  • 96
  • 123
0

Use jshint rather jslint and turn off the warning.

John
  • 5,443
  • 15
  • 21