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
  • 10,148
  • 7
  • 57
  • 107
  • 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` <-- looks like it is being used – epascarello Mar 30 '15 at 14:47
  • because someone doesn't know about `forEach`. – Evan Davis 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
  • 914,110
  • 126
  • 1,211
  • 1,335
4

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

Rene M.
  • 2,660
  • 15
  • 24
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,528
  • 1
  • 17
  • 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
  • 19,209
  • 22
  • 79
  • 122
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
  • 99,490
  • 19
  • 131
  • 169