Learn Introductory JavaScript by Building a Pyramid Generator - Step 34

Can somebody explain the concept of the iterator in simple words…
This is how freeCodeCamp explains it:
“The iterator is a variable you can declare specifically in your for loop to control how the loop iterates or goes through your logic.”
I looked up other explanations and I still don’t get it…

I think by iterator you are meaning the first expression in the brackets.

It is a variable like any other, declared usually with let. The second expression sets the condition for the variable. So if your variable is “let i = 0” the condition might by i < 5. If the condition is satisfied for the first loop, the code in the curly braces is executed. The third expression in the brackets then applies to the variable. Usually it is i++. So now the variable has increased to 1. The condition is still satisfied so the code will execute again, and will continue until the condition is not satisfied.

This article may be helpful.

1 Like

I understand the general concept of a for loop, but I don’t really understand the wording in this sentence “control how the loop iterates or goes through your logic” does that just mean it controls the number the loop starts at?

not only the number the loop starts at
you have also the other statements that build the loop

for example

for (let s = 22; s < 154; s *= 2) {
   console.log(s);
}

this is an improbable way to use a loop, but s starts at 22, then it is doubled at each iteration with s *= 2 and it will stop when it gets bigger than 154 (s < 154)

confront against

for (let i = 0; i < 5; i++) {
   console.log(i);
}

which does a different thing with the numbers

the iterator is s in one case and i in the other, how their value changes changes how the loop iterates

1 Like

I don’t completely understand what they mean by that. I think the more important thing is that you understand what the for loop is doing and how it works which you seem to understand. Once you apply it to loop through an array or an object its use becomes clearer. I am not clear what logic they are referring to in this sentence in step 34.

1 Like

Hi @itsxxtx

The iterator is a variable you can declare specifically in your for loop to control how the loop iterates or goes through your logic.

The iterator is a variable you can declare - declared like any other variable (note you have to use var or let so that the value can change)

specifically in your for loop - the variable is used just for the for loop

to control how the loop iterates or goes through your logic - the value defines the start or end point of the loop

You need to go through some examples, write some code, change some of the values to understand them better. This takes some time.

Happy coding

1 Like