Array item


#1


Hello do I have to make a variable to store the number of items of an array when making my for loop? it was introduced in this lesson. i know we could just directly use array.length directly when making the for loop.

Is it something related to best practices or what?

Secondly, why do we loop to i < contacts.length? why not i = contacts.length? is it because the array first position is 0?

Thanks for any response in advance.


var contacts.length = contactsLength;

for (var i = 0; i < contactsLength; i++) 

OR 

for (var i = 0; i < contacts.length; i++)


#2

Best practices would be to use:

contacts.length

As far as why it is

i < contacts.length

instead of

i = contacts.length

the first part of the for loop (var i = 0) is saying "here is a variable i, set equal to 0", the last part (i++) says "increment the variable i by 1 every time this loop is iterated". Finally, the middle section ( i < contacts.length) is saying, "keep going through this loop while the variable i is less than the length of contacts, once i doesn't meet this condition, jump out of the loop".


#3

Thanks for the explanation


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.