If you're seeing this message, it means we're having trouble loading external resources on our website.

If you're behind a web filter, please make sure that the domains *.kastatic.org and *.kasandbox.org are unblocked.

## Computer programming - JavaScript and the web

### Course: Computer programming - JavaScript and the web>Unit 1

Lesson 13: Looping

# Review: Looping

This is a review of what we covered in this tutorial on loops.
When we're writing programs, we often find that we want to repeat a bit of code over and over, or repeat it but change something about it each time. To save ourselves from writing all that code, we can use a loop. JavaScript has two kinds of loops, a while loop and a for loop.
A while loop is a way to repeat code until some condition is false. For example, this while loop will display the value of y at (30, y) as long as y is less than 400. The loop adds 20 to y each time it runs, so that y starts off at 40 but then increments to 60, 80, 100, 120, etc.
``````var y = 40;
while (y < 400) {
text(y, 30, y);
y += 20;
}``````
It's important that the condition inside the parenthesis becomes false at some point - otherwise we'll have what's known as an infinite loop! That's what would happen if we removed `y += 20`, because y would be 40 forever, and always be less than 400, and the program would never know when to stop.
``````var y = 40;
while (y < 400) {
text(y, 30, y);
}``````
The for loop is similar to a while loop, but with a more specialized syntax. Programmers invented the for loop when they realized they were always doing the same three things- creating loop counter variables (like y above), incrementing them by some amount, and checking that they're less than a value. A for loop syntax has special places for each of those three things. Here's the same loop as the first while loop above, as a for loop:
``````for (var y = 40; y < 400; y += 20) {
text(y, 30, y);
}``````
Loops can also be nested. It's actually very common to nest for loops, especially in 2-d drawings, because it makes it easy to draw grid-like shapes. When we nest a loop inside a loop, we're telling the program to "do this thing X many times, and for each time you do that, also do this other thing Y many times." Think about drawing a grid- we'd want to tell the program to "create a column 10 times, and for each column, also create 15 cells inside of it." Here's how you can use nested for loops to achieve that:
``````for (var col = 0; col < 10; col++) {
for (var row = 0; row < 15; row++) {
rect(col*20, row*20, 20, 20);
}
}``````
When should you use a for loop versus a while loop? That's up to you. Many programmers prefer for loops because it's harder to accidentally create an infinite loop (because it's harder to forget to increment your counter variable), but sometimes a while loop might make more sense. Try them both!

## Want to join the conversation?

• Here it is said that most programmers use for loops to avoid the risk of creating an accidental infinite loop but sometimes a while loop makes more sense.
When is a while loop preferred over a for loop ? •   A for loop is used when you know how much you need to repeat the code. However, while loops can be used if you don't know how many times you will need to repeat it.
• why do you do this?: rect(col*20, row*20, 20, 20);
why do they mutiply?
and can somebody explain to me how to use a nested for loop? it's hard to understand... •   A nested for loop is a for loop inside another for loop. It's a quick and easy way to draw multiple identical shapes in a grid. As for the code, we use variables instead of numbers for x and y values so that when the variable changes, the location of the shape will change as well. Or, in this case, changing the variable will draw another identical shape at a new location.
• In the project, Build a house you asked to use % operator to change color, how can I do that in this loop;
for(var i=0;i<400;i= i+27) {
var grass = getImage("cute/GrassBlock");
image(grass,i,350,30,50);
} •   Something like:
``for(var i=0;i<400;i= i+27) {    if(i%2===0){        fill(color1);    } else{        fill(color2);    }    rect(i,350,30,50);}``
• I feel while loops are way more easier than for loops. Does other people feel that way, or is it just me who is thinking about that? • I don't understand the variable++, can someone explain? •  It is a short hand to increment a variable.

x++; is the same as x = x + 1; it adds one to the current value of the variable.

You can also do x += 1; or x+=2; x+=200; etc. This notation allows you to add any value to the current value of the variable.

inside of a for loop it is indicating how much the variable changes every time the loop ends

for example

`for (var i = 0; i < 10; i++){}`

here you have 3 statements that control the loop.

var i = 0 states The loop is controlled by the variable i starting at the value 0

i < 10 states the continue condition of the loop. If i is less than 10 run the loop again.

*i++* indicates how the controlling variable changes each iteration of the loop.

you could just as easily count backwards

`for (var i = 10; i > 0; i--){}`

start at ten count down to 0;

or count by 2s

`for (var i = 0; i < 10; i+=2){}`
• During the Challenge; Lined Paper I kept getting the message 'It looks like you're initializing your counter variable before you create the for loop. As best practice, you should be doing that as the first expression in the for()." and I don't know exactly what you mean?
(1 vote) • Okay. Here's what the Oh Noes Guy means:
If you use a for loop,
``for(var i = 0; i<n; i++){//code};``
, the counter variable is the
``var i = 0;``
part. If, for instance, I put:
``var i = 0;for(var i = 0; i<n; i++){//code};``
, then I defined the variable before the for loop... which is what the Oh Noes Guy doesn't like. Hope this answers your question!
• If you had a loop, and you put a loop inside that loop, would you be able to keep putting loops within the previous loop for ever? • That's a bit like asking; If you have a number that you divide in half, and then you divide that result in half, can you keep dividing the halved result, in half - for ever?

Its that "for ever' part that throws a wrench into the mix. So, no, you cannot continue to nest loops for ever At some point the computer you are using will use up all of its memory trying to hold the text portion of your program.

Suffice it to say you can nest so many loops that it goes well beyond any number of loops you are reasonably likely to use.
• In my project I am trying to loop the grass but there is only one picture.

for (var grassX = 0; x < 400; x += 80){
image(getImage("cute/GrassBlock"), grassX, 268);
}   • 