0

I’m doing an exercise on Code School, and I don’t understand how the loop works.

There is an i, but I don’t see it used. Normally you use it somewhere. Otherwise, what is the for loop for?

var puzzlers = [
  function(a) { return 8 * a - 10; },
  function(a) { return (a - 3) * (a - 3) * (a - 3); },
  function(a) { return a * a + 4; },
  function(a) { return a % 5; }
];
var start = 2;

var applyAndEmpty = function(input, queue) {
  var length = queue.length;
  for (var i = 0; i < length; i++) {
    input = queue.shift()(input);
  }
  return input;
};

alert(applyAndEmpty(start, puzzlers));
TRiG
  • 9,687
  • 6
  • 54
  • 105
  • 4
    It's not used within the body of the loop, but it is used to terminate the loop after the correct number of iterations. – Matt Ball Mar 30 '15 at 14:46
  • 3
    `i < length` – epascarello Mar 30 '15 at 14:47
  • because someone doesn't know about `forEach`. – Mathletics Mar 30 '15 at 14:47
  • 1
    Knowing about `forEach` doesn't mean you'll always use it. A `for` loop is fine. They're faster. They're supported by IE8 (although forEach can be polyfilled easily enough). No need to pick on the older iteration method. ;) – bvaughn Mar 30 '15 at 14:52
  • that `for `can be easy replaced with this simpler code: `while( queue.length ){ input = queue.shift()(input); };` – albanx Mar 30 '15 at 15:01

5 Answers5

6

It's used in the test to see if you have reached the end of the loop or not (the second part of the for statement).

Quentin
  • 857,932
  • 118
  • 1,152
  • 1,264
4

Without the loop boundaries defined in the loop. The loop will never end!

Rene M.
  • 2,549
  • 12
  • 23
4

The variable is simply used to count the iterations of the loop. The loop ends after length iterations as kept track of by i.

In this case i serves no other purpose.

shibley
  • 1,408
  • 1
  • 16
  • 23
3

You don't have to use the i all the time, but its there if you need it. Normally if you dont use the i you use instead whats called a for-each loop instead. for-each is just a simpler way of writing a for loop without needing an explicit index variable.

Javascript doesn't have a simple for-each loop as part of the language, and I think they want to keep it as a for loop just to keep the lesson simple, but if you want to learn more about for-each in javascript, take a look at this question

Community
  • 1
  • 1
David says Reinstate Monica
  • 18,041
  • 20
  • 73
  • 118
3

It is being used - to ensure that the loop iterates length times.

If you are going to count from 0 to length - 1, you need something to keep track of the count, right?

JLRishe
  • 95,368
  • 17
  • 122
  • 158