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.

Main content

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?

  • male robot hal style avatar for user Enn
    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 ?
    (391 votes)
    Default Khan Academy avatar avatar for user
  • hopper jumping style avatar for user dmkim2001
    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...
    (116 votes)
    Default Khan Academy avatar avatar for user
    • leafers ultimate style avatar for user Johnny Wei
      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.
      (108 votes)
  • purple pi purple style avatar for user arjain
    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");
    (14 votes)
    Default Khan Academy avatar avatar for user
  • marcimus purple style avatar for user Thendral
    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?
    (23 votes)
    Default Khan Academy avatar avatar for user
  • starky sapling style avatar for user IsaacGranata35
    I don't understand the variable++, can someone explain?
    (4 votes)
    Default Khan Academy avatar avatar for user
    • starky sapling style avatar for user James McKinney
      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){}
      (32 votes)
  • aqualine ultimate style avatar for user Shelby
    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?
    (0 votes)
    Default Khan Academy avatar avatar for user
    • leaf red style avatar for user Blaze
      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!
      (23 votes)
  • leaf blue style avatar for user 0like.a.bird0
    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?
    (5 votes)
    Default Khan Academy avatar avatar for user
    • leaf orange style avatar for user Larry Serflaten
      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.
      (11 votes)
  • blobby green style avatar for user Falak Fathima
    Can we use other variables rather than i and j?
    (5 votes)
    Default Khan Academy avatar avatar for user
  • piceratops tree style avatar for user Raven2Sky
    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);
    (5 votes)
    Default Khan Academy avatar avatar for user
  • blobby green style avatar for user j.guliyeev
    Why a programmer needs to repeat code? are there lots of cases in programming? I mean, repetitive coding things
    (2 votes)
    Default Khan Academy avatar avatar for user
    • purple pi purple style avatar for user Alex
      That's called "code redundancy". It's always there, since a lot of processes have similar sub-processes. You can make it better by spotting redundant parts, and getting them into a function that you just call. That way you minimize redundancy.
      But sometimes it's just too much, and in the strive to end redundancy you end up with overly complex code that is very hard to modify.
      For example, you made a game, and have some code that draws a human character. You realize that drawing the human shape is redundant for each human, so you take it out into a function and just call it. But then the game progresses and you want to have short humans, tall humans, giant humans, fat humans, mutated humans, zombie humans, etc. The function deals with so many special cases, and becomes so complex, that it would just be better to be repeated everywhere it's needed, with its specific modifications each time.... or you just need a more advanced architecture.
      (12 votes)