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

Loops

I'm having a difficult time understand the syntax of the loop. I've looked at the Loop video 3 times. An example of what I don't understand.

var friends = ["Nick, "Michael", "Amit", "Allison Grayce"];
console.log(friends);
console.log(friends.length);

var friendNumber = 1;
console.log(friends[friendNumber]);

for(var i=0; i<4; i+=1)

So variable is 0. So 0 is less than 4?? And I'm having trouble with the i+=1 concept. I understand i=i+1 meaning if I put in 0 i get 1=2, 2=3. That's easier for me to understand because of the simple math. The i<4 confuses me. The length is 0 1 2 3 so <4 is the max until it becomes false?

3 Answers

for(var i=0; i<4; i+=1) Let's break this down into the components of the for loop:

  • var i=0; is declaring a variable and initial value to be used in the loop
  • i<4; this is an if statement. If i is less than 4, run the loop
  • i+=1 this is the code that is run after ever iteration of a for loop. After the loop goes through once, i will be equal to i + 1

So, as you know, the program will console.log(friends[i]); 4 times, 0 through 3.

i is set to 0, i is less than 4, console.log is run, i is incremented by 1, making it's value 1. i is less than 4, console.log runs, i is incremented by 1, making it's value 2 . . . and so on, until i is equal to 4, making the loop stop.

Does that make sense?

The I+=1 is an incrementor.

Same as saying i=i+1

So at the end of the loop, I changed to 1 from 0.

Then the loop is ran again.

Every time the loop is ran, i increments by one. Until i is no longer < 4 in this case. At that point the loop stops

Thanks guys I understand it now!!