-1

I'm just starting to learn loops, and in a for loop, if I'm looping through an array, in the second condition, I state that i < arrayName.length. I don't understand the logic here, surely it should be i = arrayName.length; Why does the length have to be < (less than) when you're looping through the entire array?

example:

var myArray = ['cats', 'dogs', 'monster munch'];

for (i = 0; i < myArray.length; i++) {
  console.log([i]);
}

Any explanation would be really useful and I'm guessing this is the same with other javascript loop structures?

Emily.

7
  • 2
    Because the index of the last item for an array with length 3 is 2 Commented Mar 21, 2017 at 22:45
  • Because the second part of a for is the condition which, if true, allows the loop to run through one more time. Commented Mar 21, 2017 at 22:45
  • developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Read through the mdn documentation. Commented Mar 21, 2017 at 22:47
  • Corresponding Wikipedia article: en.wikipedia.org/wiki/For_loop Commented Mar 21, 2017 at 22:48
  • this for loop is equivalent to var i = 0; while(i<myArray.length){ console.log(i); i++; }. And please declare your variable i, or it will end up in the global scope. Commented Mar 21, 2017 at 22:49

2 Answers 2

1

The first statement in the loop initializes i to 0, the second statement is the condition so basically it's saying "while i is less than the length... "until the statement is false. The 3rd statement is increment.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes I understand the context, I just don't understand why it uses i < myArray.length when you are looping through the entire array? Surely is should be true all the way up the i equalling the array's length, not being less than?
How would it know you're looping through the entire array? and not say another array in the same file? Futhermore, in your example you aren't exactly looping through the array, you're just repeating some tasks over until the condition is no more true. If you wanted to loop through the array you'd use for(x in myArray){do something} @EmilyChewy
0

The statement in the middle is what is called the "condition". When that statement is true, the loop continues. If it is false the loop stops.

And yes, in Javascript it is useful to note that it is the statement in the middle. You can have many initializations, and many increments, but the middle one must always be the condition. e.g.

for (var i=0; var j=10; i != j; i++; j--) {  // do stuff }

Is a valid for loop with two variable declarations and two increments. It will stop if i == j

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.