Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Not completely understanding the for loop function call of (lis[i]);

Just need some help breaking down the for loop of the code. I am not quite understanding the function call of (lis[i]);

for (let i = 0; i < lis.length; i +=1) { attachListItemButtons(lis[i]); }

1 Answer

Considering this code:

for (let i = 0; i < lis.length; i += 1) {
    attachListItemButtons(lis[i]);
}

I'm not sure exactly what the function attachListItemButtons() does, but lis appears to be an array.

Therefore, the loop is passing the value in each successive ordinal position in the array to the function attachListItemButtons() on each iteration of the loop.

In other words, if the array is:

const lis = [1, 2, 3];

then the loop, in effect would be doing this:

attachListItemButtons( 1 );
attachListItemButtons( 2 );
attachListItemButtons( 3 );

because the loop flow would be:

lis[i] == 1;
lis[i] == 2;
lis[i] == 3;

which is really:

lis[0] == 1;
lis[1] == 2;
lis[2] == 3;

One way to really see it is to code it this way:

for (let i = 0; i < lis.length; i += 1) {
    console.log(lis[i]);
    attachListItemButtons(lis[i]);
}

And look at the console output in devtools on your browser (or command line if using node).

Does that answer your question?

I hope that helps.

Stay safe and happy coding!