★ wanayoo — archive 1999 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iterationNouvelle recherche | Portail wanayoo
mozilla
Your Search Results

    Loops and iteration

    This article is in need of an editorial review.

    Summary

    Loops offer a quick and easy way to do something repeatedly. You can think of a loop as a computerized version of the game where you tell someone to take X steps in one direction then Y steps in another; for example, the idea "Go 10 steps south, then five steps to the east" could be expressed this way as a loop:

    var step;
    for (step = 0; step < 5; step++) {
        console.log('Walking east one step'); // Runs 5 times, with values of step 0 through 4.
    }
    

    There are many different kinds of loops, but they all essentially do the same thing: they repeat an action some number of times (and it's actually possible that number could be zero). The various loop mechanisms offer different ways to determine the start and end points of the loop. There are various situations that are more easily served by one type of loop over the others.

    Here's a list of the kinds of loops provided in JavaScript:

    • for(expression) { ... }
    • for ... of
    • for ... in
    • while(expression) do { ... }

    Examples

    You've already seen a simple for loop. But it can be rewritten a bit:

    var step = 0;
    for(; step < 5; step++) { ... }
    

    The same thing can be done with a while loop:

    var step = 0;
    while(step < 5) {
        console.log(step); //0,1,2,3,4
        step += 1;
    }
    

    You can read about for...of and for...in loops in detail.

    Document Tags and Contributors

    Contributors to this page: Sheppy, raqystyle, yadlapalli
    Last updated by: Sheppy,