Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Revision 1106311 of Looping code

  • Revision slug: Learn/JavaScript/Building_blocks/Looping_code
  • Revision title: Looping code
  • Revision id: 1106311
  • Created:
  • Creator: chrisdavidmills
  • Is current revision? No
  • Comment

Revision Content

{{draft}}{{PreviousMenuNext("Learn/JavaScript/Building_blocks/conditionals","Learn/JavaScript/Building_blocks/Functions", "Learn/JavaScript/Building_blocks")}}

{{IncludeSubnav("/en-US/Learn")}}

Programming languages are very useful for rapidly completing repetitive tasks, from multiple basic calculations to just about any other situation where you've got a lot of similar items of work to complete. Here we'll look at the loop structures available in JavaScript that handle such needs.

Prerequisites: Basic computer literacy, a basic understanding of HTML and CSS, JavaScript first steps.
Objective: To understand how to use loops in JavaScript.

Keep me in the loop

Loops, loops, loops. As well as being associated with popular breakfast cereals, roller coasters and musical production, they are also a critical concept in programming. Programming loops are all to do with doing the same thing over and over again — which is termed iteration in programming speak.

Let's consider the case of a farmer that is making sure he has enough food to feed his family for the week. He might use the following loop to achieve this:


A loop usually has one or more of the following features:

  •  A counter, which is initialized with a certain value — this is the starting point of the loop ("Start: I have no food", above).
  • An exit condition, which is the criteria under which the loop stops — usually the counter reaching a certain value. This is illustrated by "Have I got enough food?", above. Let's say he needs 10 portions of food to feed his family.
  • An iterator, which generally increments the counter by a small amount on each successive loop, until it reaches the exit condition. We haven't explicitly illustrated this above, but we could think about the farmer being able to collect say 2 portions of food per hour. After each hour, the amount of food he has collected is incremented by two, and he checks whether he has enough food. If he has reached 10 portions (the exit condition), he can stop collecting and go home.

In {{glossary("pseudocode")}}, this would look something like the following:

loop(food = 0; foodNeeded = 10) {
  if(food = foodNeeded) {
    exit loop;
    // We have enough food; let's go home
  } else {
    food += 2; // Spend an hour collecting 2 more food
    // loop will then run again
  }
}

So the amount of food needed is set at 10, and the amount the farmer currently has is set at 0. In each iteration of the loop we check whether the amount of food the farmer is has equal to the amount he needs. If so, we can exit the loop. If not, the farmer spends an hour collecting two portions of food, and the loop runs again.

Why bother?

At this point you probably understand the high level concepts behind loops, but you are probaly thinking "ok, great, but how does this help me write better JavaScript code?" As we said earlier, loops are all to do with doing the same thing over and over again, which is great for rapidly completing repetitive tasks.

Often, the code will be slightly different on each successive iteration of the loop, which means that you can complete a whole load of tasks that are similar but slightly different — if you've got a lot of different calculations to do, you want to do each different one, not the same one over and over again!

Let's look at an example to perfectly illustrate why loops are such a good thing. Let's say we wanted to draw 100 random circles on a {{htmlelement("canvas")}} element (press the Update button to run the example again and again to see a different random sets):

{{ EmbedLiveSample('Hidden_code', '100%', 400) }}

You don't have to understand all the code for now (you can see the full source on Github, and see the example running in a separate window), but let's look at the part of the code that actually draws the 100 circles:

for(var i = 0; i < 100; i++) {
  ctx.beginPath();
  ctx.fillStyle = 'rgba(255,0,0,0.5)';
  ctx.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 * Math.PI);
  ctx.fill();
}

You should get the basic idea — we are using a loop to run 100 iterations of this code, each one of which draws a circle in a random position on the page. The amount of code needed would be the same whether we were drawing 100 circles, 1000, or 10,000. Only one number has to change.

If we weren't using a loop here, we'd have to repeat the following code for every circle we wanted to draw:

ctx.beginPath();
ctx.fillStyle = 'rgba(255,0,0,0.5)';
ctx.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 * Math.PI);
ctx.fill();

This would get very boring and difficult to maintain very quickly. Loops really are the best.

The standard for loop

Let's start exploring some specific loop constructs. The first, which you'll use most of the time, is the for loop — this has the following syntax:

for(initializer; exit-condition; final-expression) {
  // code to run
}

Here we have:

  1. The keyword for, followed by some parentheses.
  2. Inside the parentheses we have three items, separated by semi-colons:
    1. An initializer — this is usually a variable set to a number, which is incremented to count the number of times the loop has run. It is also sometimes referred to as a counter variable.
    2. An exit-condition — as mentioned before, this defines when the loop should stop looping. This is generally an expression featuring a comparison operator, a test to see if the exit condition has been met.
    3. A final-expression — this is always evaluated (or run) each time the loop has gone through a full iteration. It usually serves to increment (or in some cases decrement) the counter variable, to bring it closer to the exit condition value.
  3. Some curly braces that contain a block of code — this code will be run each time the loop iterates.

Let's look at a real example so we can visualise what these do more clearly.

var cats = ['Bill', 'Jeff', 'Pete', 'Biggles', 'Jasmin'];
var info = 'My cats are called ';
var para = document.querySelector('p');

for(var i = 0; i < cats.length; i++) {
  info += cats[i] + ', ';
}

info += '.'

para.textContent = info;

This gives us the following output:

{{ EmbedLiveSample('Hidden_code_2', '100%', 50) }}

Note: You can find this example code on GitHub too (also see it running live).

This shows a loop being used to iterate over the items in an array and do something with each of them — a very common pattern in JavaScript. Here:

  1. The iterator, i, starts at 0 (var i = 0).
  2. It has been told to run until it is no longer smaller than the length of the cats array. This is important — the exit condition shows the condition under which the loop will still run. So in this case, while i < cats.length is still true, the loop will still run.
  3. Inside the loop, we concatenate the current loop item (cats[i] is cats[whatever i is at the time]) along with a comma and a space, onto the end of the info variable. So:
    1. During the first run, i = 0, so cats[0] + ', ' will be concatenated onto info ("Bill, ").
    2. During the second run, i = 1, so cats[1] + ', ' will be concatenated onto info ("Jeff, ")
    3. And so on. After each time the loop has run, 1 will be added to i (i++), then the process will start again.
  4. When i becomes equal to cats.length, the loop will stop, and the browser will move on to the next bit of code below the loop.

Note: We have made the exit condition i < cats.length, not i <= cats.length, because computers count from 0, not 1 — we are starting i at 0, and going up to i = 4 (the index of the last array item). cats.length returns 5, as there are 5 items in the array, but we don't want to get up to i = 5, as that would return undefined for the last item (there is no array item with an index of 5). So therefore we want to go up to 1 less than cats.length (i <), not the same as cats.length (i <=).

Note: A common mistake with exit conditions is making them use "equal to" rather than say "less than or equal to". If we wanted to run our loop up to i = 5, the exit condition would need to be i <= cats.length/ If we set it to i = cats.length, the loop would not run at all because i is not equal to 5 on the first loop iteration, so it would stop immediately.

One small problem we are left with is that the final output sentence isn't very well-formed:

My cats are called Bill, Jeff, Pete, Biggles, Jasmin,

Ideally we want to change the concatenation on the final loop iteration so that we haven't got a comma on the end of the sentence. Well, no problem — we can quite happily insert a conditional inside our for loop to handle this special case:

for(var i = 0; i < cats.length; i++) {
  if(i === cats.length - 1) {
    info += 'and ' + cats[i] + '.';
  } else {
    info += cats[i] + ', ';
  }
}

Important: With for — as with all loops — you must make sure that the initializer is iterated so that it eventually reaches the exit condition. If not, the loop will go on forever, and either the browser will force it to stop, or it wil crash. Thisis called an infinite loop.

Exiting loops with break

If you want to exit a loop before all the iterations have been completed, you can use the break statement. We already met this in the previous article when we looked at switch statements — when a case is met in a switch statement that matches the input expression, the break statement immediately exits the switch statement and moves onto the code after it.

It's the same with loops — a break statement will immediately exit the loop and make the browser move on to any code that follows it.

Say we wanted to search through an array of contacts and telephone numbers and return just the number we wanted to find? First, some simple HTML — a text {{htmlelement("input")}} allowing us to enter a name to search for, a {{htmlelement("button")}} element to submit a search, and a {{htmlelement("p")}} element to display the results in:

<label for="search">Search by contact name: </label>
<input id="search" type="text">
<button>Search</button>

<p></p>

Now on to the JavaScript:

var contacts = ['Chris:2232322', 'Sarah:3453456', 'Bill:7654322', 'Mary:9998769', 'Dianne:9384975'];
var para = document.querySelector('p');
var input = document.querySelector('input');
var btn = document.querySelector('button');

btn.addEventListener('click', function() {
  var searchName = input.value;
  input.value = '';
  input.focus();
  for(var i = 0; i < contacts.length; i++) {
    var splitContact = contacts[i].split(':');
    if(splitContact[0] === searchName) {
      para.textContent = splitContact[0] + '\'s number is ' + splitContact[1] + '.';
      break;
    } else {
      para.textContent = 'Contact not found.';
    }
  }
});

{{ EmbedLiveSample('Hidden_code_3', '100%', 150) }}

  1. First of all we have some variable definitions — we have an array of contact information, with each item being a string containing a name and phone number separated by a colon.
  2. Next, we attach an event listener to the button (btn), so that when it is pressed, some code is run to perform the search and return the results.
  3. We store the value entered into the text input in a variable called searchName, before then emptying the text input and focusing it again, ready for the next search.
  4. Now onto the interesting part, the for loop:
    1. We start the counter at 0, run the loop until the counter is no longer less than contacts.length, and increment i by 1 after each iteration of the loop.
    2. Inside the loop we first split the current contact (contacts[i]) at the colon character, and store the resulting two values in an array called splitContact.
    3. We then use a conditional statement to test whether splitContact[0] (the contact's name) is equal to the inputted searchName. If it is, we enter a string into the paragraph to report what the contact's number is, and use break to end the loop.
  5. If the contact name does not match the entered search, the paragraph text is set to "Contact not found.", and the loop continues iterating.

Skipping iterations with continue

The continue statement works in a similar manner to break, but instead of breaking out of the loop entirely, it skips to the next iteration of the loop. Let's look at another example that takes a number as an input, and returns only the numbers that are squares of integers (whole numbers).

The HTML is basically the same as the last example — a simple text input, and a paragraph for output. The JavaScript is mostly the same too, although the loop itself is a bit different:

var num = input.value;

for (var i = 1; i <= num; i++) {
  var sqRoot = Math.sqrt(i);
  if(Math.floor(sqRoot) !== sqRoot) {
    continue;
  }

  para.textContent += i + ' ';
}

Here's the output:

{{ EmbedLiveSample('Hidden_code_4', '100%', 150) }}

  1. In this case, the input should be a number (num). The for loop is given a counter starting at 1 (as we are not interested in 0 in this case), an exit condition that says the loop will stop when the counter becomes bigger than the input num, and an iterator that adds 1 to the counter each time.
  2. Inside the loop, we find the square root of each number using Math.sqrt(i), then check whether the square root is an integer by testing whether it is the same as itself when it has been rounded down to the nearest integer (this is what Math.floor() does to the number it is passed).
  3. If the square root and the rounded down square root do not equal one another (!==), it means that the square root is not an integer, so we are not interested in it. In such a case, we use the continue statement to skip on to the next loop iteration without recording the number anywhere.
  4. If the square root IS an integer, we skip past the if block entirely so the continue statement is not executed; instead, we concatenate the current i value plus a space on to the end of the paragraph content.

Note: You can view the full source code on GitHub, and see it running live there too.

while and do ... while

for is not the only type of loop available in JavaScript. There are actually many others and, while you don't need to understand all of these now, it is worth having a look at the structure of a couple of others so that you can recognise the same features at work in a slightly different way.

First, let's have a look at the while loop. This loop's syntax looks like so:

initializer
while(exit-condition) {
  // code to run

  final-expression
}

This works in a very similar way to the for loop, except that the initializer variable is set before the loop, and the final-expression is included inside the loop after the code to run — rather than these two items being included inside the parentheses. The exit-condition is included inside the parentheses, which are preceded by the while keyword rather than for.

The same three items are still present, and they are still defined in the same order as they are in the for loop — this makes sense, as you still have to have an initializer defined before you can check whether it has reached the exit-condition; the final-condition is then run after the code inside the loop has run (an iteration has been completed), which will only happen if the exit-condition has still not been reached.

Let's have a look again at our cats list example, but rewritten to use a while loop:

var i = 0;

while(i < cats.length) {
  if(i === cats.length - 1) {
    info += 'and ' + cats[i] + '.';
  } else {
    info += cats[i] + ', ';
  }

  i++;
}

Note: This still works just the same as expected — have a look at it running live on GitHub (also view the full source code).

The do...while loop is very similar, but provides a variation on the while structure:

initializer
do {
  // code to run

  final-expression
} while(exit-condition)

In this case, the initializer again comes first, before the loop starts. The do keyword directly precedes the curly braces containing the code to run and the final-expression.

The differentiator here is that the exit-condition comes after everything else, wrapped in parentheses and preceded by a while keyword. In a do...while loop, the code inside the curly braces is always run once before the check is made to see if it should be executed again (in while and for, the check comes first, so the code might never be executed).

Let's rewrite our cat listing example again to use a do...while loop:

var i = 0;

do {
  if(i === cats.length - 1) {
    info += 'and ' + cats[i] + '.';
  } else {
    info += cats[i] + ', ';
  }

  i++;
} while(i < cats.length);

Note: Again, this works just the same as expected — have a look at it running live on GitHub (also view the full source code).

Important: With while and do...while — as with all loops — you must make sure that the initializer is iterated so that it eventually reaches the exit condition. If not, the loop will go on forever, and either the browser will force it to stop, or it wil crash. Thisis called an infinite loop.

Active learning: Launch countdown!

In this exercise, we want you to print out a simple launch countdown to the output box, from 10 down to Blast off. Specifically, we want you to:

  • Loop from 10 down to 0. We've provided you with an initializer — var i = 10;.
  • For each iteration, create a new paragraph and append it to the output <div>, which we've selected using var output = document.querySelector('.output');. In comments, we've provided you with:
    • var para = document.createElement('p'); — creates a new paragraph.
    • output.appendChild(para); — appends the paragraph to the output <div>.
    • para.textContent = — makes the text inside the paragraph equal to whatever you put on the right hand side, after the equals sign.
  • Different iterations require different text to be put in the paragraph for that iteration:
    • If the number is 10, print "Countdown 10" to the paragraph.
    • If the number is 0, print "Blast off!" to the paragraph.
    • For any other number, print just the number to the paragraph.
  • Include an iterator! However, in this example we are counting down after each iteration, not up.

If you make a mistake, you can always reset the example with the "Reset" button. If you get really stuck, press "Show solution" to see a solution.

{{ EmbedLiveSample('Active_learning', '100%', 800) }}

Active learning: Filling in a guest list

In this exercise, we want you to take a list of names stored in an array, and put them into a guest list. But it's not quite that easy — we don't want to let Phil and Lola in because they are greedy and rude, and always eat all the food! We have two lists, one for guests to admit, and one for guests to refuse.

Specifically, we want you to:

  • Write a loop that will iterate from 0 to the length of the people array.
  • During each loop iteration, check if the current array item is equal to "Phil" or "Lola":
    • If it is, concatenate the array item to the end of the refused paragraph's textContent, followed by a comma and a space.
    • If it isn't, concatenate the array item to the end of the admitted paragraph's textContent, followed by a comma and a space.

We've already provided you with:

  • var i = 0; — An initializer
  • refused.textContent += — the beginnings of a line that will concatenate something on to the end of refused.textContent.
  • admitted.textContent += — the beginnings of a line that will concatenate something on to the end of admitted.textContent.

Extra bonus question — after completing the above tasks successfully, you will be left with two lists of names, separated by commas, but they will be untidy — there will be a comma at the end of each one. Can you work out how to write lines that slice the last comma off in each case, and add a full stop to the end?

If you make a mistake, you can always reset the example with the "Reset" button. If you get really stuck, press "Show solution" to see a solution.

{{ EmbedLiveSample('Active_learning_2', '100%', 800) }}

Which loop type should you use?

For basic uses, for, while, and do...while loops are largely interchangeable. They can all be used to solve the same problems, and which one you use will largely depend on your personal preference — which one you find easiest to remember or most intuitive. Let's have a look at them again.

First for:

for(initializer; exit-condition; final-expression) {
  // code to run
}

while:

initializer
while(exit-condition) {
  // code to run

  final-expression
}

and finally do...while:

initializer
do {
  // code to run

  final-expression
} while(exit-condition)

We would recommend for, at least to begin with, as it is probably the easiest for remembering everything — the initializer, exit-condition, and final-expression all have to go neatly into the parentheses, so it is easy to see where they are and check that you aren't missing them.

Note: There are other loop types/features too, which are useful in advanced/specialized situations and beyond the scope of this article. If you want to go further with your loop learning, read our advanced Loops and iteration guide.

Conclusion

This article has revealed to you the basic concepts behind, and different options available when, looping code in JavaScript. You should now be clear on why loops are a good mechanism for dealing with repetitive code, and be raring to use them in your own examples!

If there is anything you didn't understand, feel free to read through the article again, or contact us to ask for help.

See also

{{PreviousMenuNext("Learn/JavaScript/Building_blocks/conditionals","Learn/JavaScript/Building_blocks/Functions", "Learn/JavaScript/Building_blocks")}}

Revision Source

<p>{{draft}}{{PreviousMenuNext("Learn/JavaScript/Building_blocks/conditionals","Learn/JavaScript/Building_blocks/Functions", "Learn/JavaScript/Building_blocks")}}</p>

<div>{{IncludeSubnav("/en-US/Learn")}}</div>

<p class="summary">Programming languages are very useful for rapidly completing repetitive tasks, from multiple basic calculations to just about any other situation where you've got a lot of similar items of work to complete. Here we'll look at the loop structures available in JavaScript that handle such needs.</p>

<table class="learn-box standard-table">
 <tbody>
  <tr>
   <th scope="row">Prerequisites:</th>
   <td>Basic computer literacy, a basic understanding of HTML and CSS, <a href="/en-US/docs/Learn/JavaScript/First_steps">JavaScript first steps</a>.</td>
  </tr>
  <tr>
   <th scope="row">Objective:</th>
   <td>To understand how to use loops in JavaScript.</td>
  </tr>
 </tbody>
</table>

<h2 id="Keep_me_in_the_loop">Keep me in the loop</h2>

<p>Loops, loops, loops. As well as being associated with <a href="https://en.wikipedia.org/wiki/Froot_Loops">popular breakfast cereals</a>, <a href="https://en.wikipedia.org/wiki/Vertical_loop">roller coasters</a> and <a href="https://en.wikipedia.org/wiki/Loop_(music)">musical production</a>, they are also a critical concept in programming. Programming loops are all to do with doing the same thing over and over again — which is termed <strong>iteration</strong> in programming speak.</p>

<p>Let's consider the case of a farmer that is making sure he has enough food to feed his family for the week. He might use the following loop to achieve this:</p>

<p><br />
 <img alt="" src="https://mdn.mozillademos.org/files/13755/loop_js-02-farm.png" style="display:block; margin:0 auto" /></p>

<p>A loop usually has one or more of the following features:</p>

<ul>
 <li>&nbsp;A <strong>counter</strong>, which is initialized with a certain value — this is the starting point of the loop ("Start: I have no food", above).</li>
 <li>An <strong>exit condition</strong>, which is the criteria under which the loop stops — usually the counter reaching a certain value. This is illustrated by "Have I got enough food?", above. Let's say he needs 10 portions of food to feed his family.</li>
 <li>An <strong>iterator</strong>, which generally increments the counter by a small amount on each successive loop, until it reaches the exit condition. We haven't explicitly illustrated this above, but we could think about the farmer being able to collect say 2 portions of food per hour. After each hour, the amount of food he has collected is incremented by two, and he checks whether he has enough food. If he has reached 10 portions (the exit condition), he can stop collecting and go home.</li>
</ul>

<p>In {{glossary("pseudocode")}}, this would look something like the following:</p>

<pre>
loop(food = 0; foodNeeded = 10) {
  if(food = foodNeeded) {
    exit loop;
    // We have enough food; let's go home
  } else {
    food += 2; // Spend an hour collecting 2 more food
    // loop will then run again
  }
}</pre>

<p>So the amount of food needed is set at 10, and the amount the farmer currently has is set at 0. In each iteration of the loop we check whether the amount of food the farmer is has equal to the amount he needs. If so, we can exit the loop. If not, the farmer spends an hour collecting two portions of food, and the loop runs again.</p>

<h3 id="Why_bother">Why bother?</h3>

<p>At this point you probably understand the high level concepts behind loops, but you are probaly thinking "ok, great, but how does this help me write better JavaScript code?" As we said earlier, <strong>loops are all to do with doing the same thing over and over again</strong>, which is great for <strong>rapidly completing repetitive tasks</strong>.</p>

<p>Often, the code will be slightly different on each successive iteration of the loop, which means that you can complete a whole load of tasks that are similar but slightly different — if you've got a lot of different calculations to do, you want to do each different one, not the same one over and over again!</p>

<p>Let's look at an example to perfectly illustrate why loops are such a good thing. Let's say we wanted to draw 100 random circles on a {{htmlelement("canvas")}} element (press the <em>Update</em> button to run the example again and again to see a different random sets):</p>

<div class="hidden">
<h6 id="Hidden_code">Hidden code</h6>

<pre class="brush: html">
&lt;!DOCTYPE html&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;meta charset="utf-8"&gt;
    &lt;title&gt;Random canvas circles&lt;/title&gt;
    &lt;style&gt;
      html {
        width: 100%;
        height: inherit;
        background: #ddd;
      }

      canvas {
        display: block;
      }

      body {
        margin: 0;
      }

      button {
        position: absolute;
        top: 5px;
        left: 5px;
      }
    &lt;/style&gt;
  &lt;/head&gt;
  &lt;body&gt;

  &lt;button&gt;Update&lt;/button&gt;

  &lt;canvas&gt;&lt;/canvas&gt;
    

    &lt;script&gt;
    var btn = document.querySelector('button');
    var canvas = document.querySelector('canvas');
    var ctx = canvas.getContext('2d');

    var WIDTH = document.documentElement.clientWidth;
    var HEIGHT = document.documentElement.clientHeight;

    canvas.width = WIDTH;
    canvas.height = HEIGHT;

    function random(number) {
      return Math.floor(Math.random()*number);
    }

    function draw() {
      ctx.clearRect(0,0,WIDTH,HEIGHT);
      for(var i = 0; i &lt; 100; i++) {
        ctx.beginPath();
        ctx.fillStyle = 'rgba(255,0,0,0.5)';
        ctx.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 * Math.PI);
        ctx.fill();
      }
    }

    btn.addEventListener('click',draw);
      
    &lt;/script&gt;
    
  &lt;/body&gt;
&lt;/html&gt;</pre>
</div>

<p>{{ EmbedLiveSample('Hidden_code', '100%', 400) }}</p>

<p>You don't have to understand all the code for now (you can see the full source on Github, and see the example running in a separate window), but let's look at the part of the code that actually draws the 100 circles:</p>

<pre class="brush: js">
for(var i = 0; i &lt; 100; i++) {
  ctx.beginPath();
  ctx.fillStyle = 'rgba(255,0,0,0.5)';
  ctx.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 * Math.PI);
  ctx.fill();
}</pre>

<p>You should get the basic idea — we are using a loop to run 100 iterations of this code, each one of which draws a circle in a random position on the page. The amount of code needed would be the same whether we were drawing 100 circles, 1000, or 10,000. Only one number has to change.</p>

<p>If we weren't using a loop here, we'd have to repeat the following code for every circle we wanted to draw:</p>

<pre class="brush: js">
ctx.beginPath();
ctx.fillStyle = 'rgba(255,0,0,0.5)';
ctx.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 * Math.PI);
ctx.fill();</pre>

<p>This would get very boring and difficult to maintain very quickly. Loops really are the best.</p>

<h2 id="The_standard_for_loop">The standard for loop</h2>

<p>Let's start exploring some specific loop constructs. The first, which you'll use most of the time, is the <a href="/en-US/docs/Web/JavaScript/Reference/Statements/for">for</a> loop — this has the following syntax:</p>

<pre>
for(initializer; exit-condition; final-expression) {
  // code to run
}</pre>

<p>Here we have:</p>

<ol>
 <li>The keyword <code>for</code>, followed by some parentheses.</li>
 <li>Inside the parentheses we have three items, separated by semi-colons:
  <ol>
   <li>An <strong>initializer</strong> — this is usually a variable set to a number, which is incremented to count the number of times the loop has run. It is also sometimes referred to as a <strong>counter variable</strong>.</li>
   <li>An <strong>exit-condition</strong> — as mentioned before, this defines when the loop should stop looping. This is generally an expression featuring a comparison operator, a test to see if the exit condition has been met.</li>
   <li>A <strong>final-expression</strong> — this is always evaluated (or run) each time the loop has gone through a full iteration. It usually serves to increment (or in some cases decrement) the counter variable, to bring it closer to the exit condition value.</li>
  </ol>
 </li>
 <li>Some curly braces that contain a block of code — this code will be run each time the loop iterates.</li>
</ol>

<p>Let's look at a real example so we can visualise what these do more clearly.</p>

<pre class="brush: js">
var cats = ['Bill', 'Jeff', 'Pete', 'Biggles', 'Jasmin'];
var info = 'My cats are called ';
var para = document.querySelector('p');

for(var i = 0; i &lt; cats.length; i++) {
  info += cats[i] + ', ';
}

info += '.'

para.textContent = info;</pre>

<p>This gives us the following output:</p>

<div class="hidden">
<h6 id="Hidden_code_2">Hidden code 2</h6>

<pre class="brush: html">
&lt;!DOCTYPE html&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;meta charset="utf-8"&gt;
    &lt;title&gt;Basic for loop example&lt;/title&gt;
    &lt;style&gt;
      
    &lt;/style&gt;
  &lt;/head&gt;
  &lt;body&gt;

  &lt;p&gt;&lt;/p&gt;
    

    &lt;script&gt;
    var cats = ['Bill', 'Jeff', 'Pete', 'Biggles', 'Jasmin'];
    var info = 'My cats are called ';
    var para = document.querySelector('p');

    for(var i = 0; i &lt; cats.length; i++) {
      info += cats[i] + ', ';
    }

    para.textContent = info;
      
    &lt;/script&gt;
    
  &lt;/body&gt;
&lt;/html&gt;</pre>
</div>

<p>{{ EmbedLiveSample('Hidden_code_2', '100%', 50) }}</p>

<div class="note">
<p><strong>Note</strong>: You can find this <a href="https://github.com/mdn/learning-area/blob/master/javascript/building-blocks/loops/basic-for.html">example code on GitHub</a> too (also <a href="https://mdn.github.io/learning-area/javascript/building-blocks/loops/basic-for.html">see it running live</a>).</p>
</div>

<p>This shows a loop being used to iterate over the items in an array and do something with each of them — a very common pattern in JavaScript. Here:</p>

<ol>
 <li>The iterator, <code>i</code>, starts at <code>0</code> (<code>var i = 0</code>).</li>
 <li>It has been told to run until it is no longer smaller than the length of the cats array. This is important — the exit condition shows the condition under which the loop will still run. So in this case, while <code>i &lt; cats.length</code> is still true, the loop will still run.</li>
 <li>Inside the loop, we concatenate the current loop item (<code>cats[i]</code> is <code>cats[whatever i is at the time]</code>) along with a comma and a space, onto the end of the <code>info</code> variable. So:
  <ol>
   <li>During the first run, <code>i = 0</code>, so <code>cats[0] + ', '</code> will be concatenated onto info ("Bill, ").</li>
   <li>During the second run, <code>i = 1</code>, so <code>cats[1] + ', '</code> will be concatenated onto info ("Jeff, ")</li>
   <li>And so on. After each time the loop has run, 1 will be added to <code>i</code> (<code>i++</code>), then the process will start again.</li>
  </ol>
 </li>
 <li>When <code>i</code> becomes equal to <code>cats.length</code>, the loop will stop, and the browser will move on to the next bit of code below the loop.</li>
</ol>

<div class="note">
<p><strong>Note</strong>: We have made the exit condition <code>i &lt; cats.length</code>, not <code>i &lt;= cats.length</code>, because computers count from 0, not 1 — we are starting <code>i</code> at <code>0</code>, and going up to <code>i = 4</code> (the index of the last array item). <code>cats.length</code> returns 5, as there are 5 items in the array, but we don't want to get up to <code>i = 5</code>, as that would return <code>undefined</code> for the last item (there is no array item with an index of 5). So therefore we want to go up to 1 less than <code>cats.length</code> (<code>i &lt;</code>), not the same as <code>cats.length</code> (<code>i &lt;=</code>).</p>
</div>

<div class="note">
<p><strong>Note</strong>: A common mistake with exit conditions is making them use "equal to" rather than say "less than or equal to". If we wanted to run our loop up to i = 5, the exit condition would need to be i &lt;= cats.length/ If we set it to i = cats.length, the loop would not run at all because i is not equal to 5 on the first loop iteration, so it would stop immediately.</p>
</div>

<p>One small problem we are left with is that the final output sentence isn't very well-formed:</p>

<blockquote>
<p>My cats are called Bill, Jeff, Pete, Biggles, Jasmin,</p>
</blockquote>

<p>Ideally we want to change the concatenation on the final loop iteration so that we haven't got a comma on the end of the sentence. Well, no problem — we can quite happily insert a conditional inside our for loop to handle this special case:</p>

<pre class="brush: js">
for(var i = 0; i &lt; cats.length; i++) {
  if(i === cats.length - 1) {
    info += 'and ' + cats[i] + '.';
  } else {
    info += cats[i] + ', ';
  }
}</pre>

<div class="note">
<p><strong>Note</strong>: You can <a href="https://github.com/mdn/learning-area/blob/master/javascript/building-blocks/loops/basic-for-improved.html">find this example code on GitHub</a> too (also <a href="https://mdn.github.io/learning-area/javascript/building-blocks/loops/basic-for-improved.html">see it running live</a>).</p>
</div>

<div class="warning">
<p><strong>Important</strong>: With for — as with all loops — you must make sure that the initializer is iterated so that it eventually reaches the exit condition. If not, the loop will go on forever, and either the browser will force it to stop, or it wil crash. Thisis called an <strong>infinite loop</strong>.</p>
</div>

<h2 id="Exiting_loops_with_break">Exiting loops with break</h2>

<p>If you want to exit a loop before all the iterations have been completed, you can use the <a href="/en-US/docs/Web/JavaScript/Reference/Statements/break">break</a> statement. We already met this in the previous article when we looked at <a href="/en-US/Learn/JavaScript/Building_blocks/conditionals#switch_statements">switch statements</a> — when a case is met in a switch statement that matches the input expression, the break statement immediately exits the switch statement and moves onto the code after it.</p>

<p>It's the same with loops — a <code>break</code> statement will immediately exit the loop and make the browser move on to any code that follows it.</p>

<p>Say we wanted to search through an array of contacts and telephone numbers and return just the number we wanted to find? First, some simple HTML — a text {{htmlelement("input")}} allowing us to enter a name to search for, a {{htmlelement("button")}} element to submit a search, and a {{htmlelement("p")}} element to display the results in:</p>

<pre class="brush: html">
&lt;label for="search"&gt;Search by contact name: &lt;/label&gt;
&lt;input id="search" type="text"&gt;
&lt;button&gt;Search&lt;/button&gt;

&lt;p&gt;&lt;/p&gt;</pre>

<p>Now on to the JavaScript:</p>

<pre class="brush: js">
var contacts = ['Chris:2232322', 'Sarah:3453456', 'Bill:7654322', 'Mary:9998769', 'Dianne:9384975'];
var para = document.querySelector('p');
var input = document.querySelector('input');
var btn = document.querySelector('button');

btn.addEventListener('click', function() {
  var searchName = input.value;
  input.value = '';
  input.focus();
  for(var i = 0; i &lt; contacts.length; i++) {
    var splitContact = contacts[i].split(':');
    if(splitContact[0] === searchName) {
      para.textContent = splitContact[0] + '\'s number is ' + splitContact[1] + '.';
      break;
    } else {
      para.textContent = 'Contact not found.';
    }
  }
});</pre>

<div class="hidden">
<h6 id="Hidden_code_3">Hidden code 3</h6>

<pre class="brush: html">
&lt;!DOCTYPE html&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;meta charset="utf-8"&gt;
    &lt;title&gt;Simple contact search example&lt;/title&gt;
    &lt;style&gt;
      
    &lt;/style&gt;
  &lt;/head&gt;
  &lt;body&gt;

  &lt;label for="search"&gt;Search by contact name: &lt;/label&gt;
  &lt;input id="search" type="text"&gt;
  &lt;button&gt;Search&lt;/button&gt;

  &lt;p&gt;&lt;/p&gt;
    

    &lt;script&gt;
    var contacts = ['Chris:2232322', 'Sarah:3453456', 'Bill:7654322', 'Mary:9998769', 'Dianne:9384975'];
    var para = document.querySelector('p');
    var input = document.querySelector('input');
    var btn = document.querySelector('button');

    btn.addEventListener('click', function() {
      var searchName = input.value;
      input.value = '';
      input.focus();
      for(var i = 0; i &lt; contacts.length; i++) {
        var splitContact = contacts[i].split(':');
        if(splitContact[0] === searchName) {
          para.textContent = splitContact[0] + '\'s number is ' + splitContact[1] + '.';
          break;
        } else {
          para.textContent = 'Contact not found.';
        }
      }
    });  
    &lt;/script&gt;
    
  &lt;/body&gt;
&lt;/html&gt;</pre>
</div>

<p>{{ EmbedLiveSample('Hidden_code_3', '100%', 150) }}</p>

<ol>
 <li>First of all we have some variable definitions — we have an array of contact information, with each item being a string containing a name and phone number separated by a colon.</li>
 <li>Next, we attach an event listener to the button (<code>btn</code>), so that when it is pressed, some code is run to perform the search and return the results.</li>
 <li>We store the value entered into the text input in a variable called <code>searchName</code>, before then emptying the text input and focusing it again, ready for the next search.</li>
 <li>Now onto the interesting part, the for loop:
  <ol>
   <li>We start the counter at <code>0</code>, run the loop until the counter is no longer less than <code>contacts.length</code>, and increment <code>i</code> by 1 after each iteration of the loop.</li>
   <li>Inside the loop we first split the current contact (<code>contacts[i]</code>) at the colon character, and store the resulting two values in an array called <code>splitContact</code>.</li>
   <li>We then use a conditional statement to test whether <code>splitContact[0]</code> (the contact's name) is equal to the inputted <code>searchName</code>. If it is, we enter a string into the paragraph to report what the contact's number is, and use <code>break</code> to end the loop.</li>
  </ol>
 </li>
 <li>If the contact name does not match the entered search, the paragraph text is set to "Contact not found.", and the loop continues iterating.</li>
</ol>

<div class="note">
<p>Note: You can <a href="https://github.com/mdn/learning-area/blob/master/javascript/building-blocks/loops/contact-search.html">view the full source code on GitHub</a>, and <a href="https://mdn.github.io/learning-area/javascript/building-blocks/loops/contact-search.html">see it running live</a> there too.</p>
</div>

<h2 id="Skipping_iterations_with_continue">Skipping iterations with continue</h2>

<p>The <a href="/en-US/docs/Web/JavaScript/Reference/Statements/continue">continue</a> statement works in a similar manner to <code>break</code>, but instead of breaking out of the loop entirely, it skips to the next iteration of the loop. Let's look at another example that takes a number as an input, and returns only the numbers that are squares of integers (whole numbers).</p>

<p>The HTML is basically the same as the last example — a simple text input, and a paragraph for output. The JavaScript is mostly the same too, although the loop itself is a bit different:</p>

<pre>
var num = input.value;

for (var i = 1; i &lt;= num; i++) {
  var sqRoot = Math.sqrt(i);
  if(Math.floor(sqRoot) !== sqRoot) {
    continue;
  }

  para.textContent += i + ' ';
}</pre>

<p>Here's the output:</p>

<div class="hidden">
<h6 id="Hidden_code_4">Hidden code 4</h6>

<pre class="brush: html">
&lt;!DOCTYPE html&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;meta charset="utf-8"&gt;
    &lt;title&gt;Integer squares generator&lt;/title&gt;
    &lt;style&gt;
      
    &lt;/style&gt;
  &lt;/head&gt;
  &lt;body&gt;

  &lt;label for="number"&gt;Enter number: &lt;/label&gt;
  &lt;input id="number" type="text"&gt;
  &lt;button&gt;Generate integer squares&lt;/button&gt;

  &lt;p&gt;Output: &lt;/p&gt;
    

    &lt;script&gt;
    var para = document.querySelector('p');
    var input = document.querySelector('input');
    var btn = document.querySelector('button');

    btn.addEventListener('click', function() {
      para.textContent = 'Output: ';
      var num = input.value;
      input.value = '';
      input.focus();
      for (var i = 1; i &lt;= num; i++) {
        var sqRoot = Math.sqrt(i);
        if(Math.floor(sqRoot) !== sqRoot) {
          continue;
        }

        para.textContent += i + ' ';
      }
    });  
    &lt;/script&gt;
    
  &lt;/body&gt;
&lt;/html&gt;</pre>
</div>

<p>{{ EmbedLiveSample('Hidden_code_4', '100%', 150) }}</p>

<ol>
 <li>In this case, the input should be a number (<code>num</code>). The <code>for</code> loop is given a counter starting at 1 (as we are not interested in 0 in this case), an exit condition that says the loop will stop when the counter becomes bigger than the input <code>num</code>, and an iterator that adds 1 to the counter each time.</li>
 <li>Inside the loop, we find the square root of each number using <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sqrt">Math.sqrt(i)</a>, then check whether the square root is an integer by testing whether it is the same as itself when it has been rounded down to the nearest integer (this is what <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor">Math.floor()</a> does to the number it is passed).</li>
 <li>If the square root and the rounded down square root do not equal one another (<code>!==</code>), it means that the square root is not an integer, so we are not interested in it. In such a case, we use the <code>continue</code> statement to skip on to the next loop iteration without recording the number anywhere.</li>
 <li>If the square root IS an integer, we skip past the if block entirely so the <code>continue</code> statement is not executed; instead, we concatenate the current <code>i</code> value plus a space on to the end of the paragraph content.</li>
</ol>

<div class="note">
<p><strong>Note</strong>: You can view the <a href="https://github.com/mdn/learning-area/blob/master/javascript/building-blocks/loops/integer-squares.html">full source code on GitHub</a>, and <a href="https://mdn.github.io/learning-area/javascript/building-blocks/loops/integer-squares.html">see it running live</a> there too.</p>
</div>

<h2 id="while_and_do_..._while">while and do ... while</h2>

<p><code>for</code> is not the only type of loop available in JavaScript. There are actually many others and, while you don't need to understand all of these now, it is worth having a look at the structure of a couple of others so that you can recognise the same features at work in a slightly different way.</p>

<p>First, let's have a look at the <a href="/en-US/docs/Web/JavaScript/Reference/Statements/while">while</a> loop. This loop's syntax looks like so:</p>

<pre>
initializer
while(exit-condition) {
  // code to run

  final-expression
}</pre>

<p>This works in a very similar way to the for loop, except that the initializer variable is set before the loop, and the final-expression is included inside the loop after the code to run — rather than these two items being included inside the parentheses. The exit-condition is included inside the parentheses, which are preceded by the <code>while</code> keyword rather than <code>for</code>.</p>

<p>The same three items are still present, and they are still defined in the same order as they are in the for loop — this makes sense, as you still have to have an initializer defined before you can check whether it has reached the exit-condition; the final-condition is then run after the code inside the loop has run (an iteration has been completed), which will only happen if the exit-condition has still not been reached.</p>

<p>Let's have a look again at our cats list example, but rewritten to use a while loop:</p>

<pre class="brush: js">
var i = 0;

while(i &lt; cats.length) {
  if(i === cats.length - 1) {
    info += 'and ' + cats[i] + '.';
  } else {
    info += cats[i] + ', ';
  }

  i++;
}</pre>

<div class="note">
<p><strong>Note</strong>: This still works just the same as expected — have a look at it <a href="https://mdn.github.io/learning-area/javascript/building-blocks/loops/while.html">running live on GitHub</a> (also view the <a href="https://github.com/mdn/learning-area/blob/master/javascript/building-blocks/loops/while.html">full source code</a>).</p>
</div>

<p>The <a href="/en-US/docs/Web/JavaScript/Reference/Statements/do...while">do...while</a> loop is very similar, but provides a variation on the while structure:</p>

<pre>
initializer
do {
  // code to run

  final-expression
} while(exit-condition)</pre>

<p>In this case, the initializer again comes first, before the loop starts. The <code>do</code> keyword directly precedes the curly braces containing the code to run and the final-expression.</p>

<p>The differentiator here is that the exit-condition comes after everything else, wrapped in parentheses and preceded by a <code>while</code> keyword. In a <code>do...while</code> loop, the code inside the curly braces is always run once before the check is made to see if it should be executed again (in while and for, the check comes first, so the code might never be executed).</p>

<p>Let's rewrite our cat listing example again to use a <code>do...while</code> loop:</p>

<pre class="brush: js">
var i = 0;

do {
  if(i === cats.length - 1) {
    info += 'and ' + cats[i] + '.';
  } else {
    info += cats[i] + ', ';
  }

  i++;
} while(i &lt; cats.length);</pre>

<div class="note">
<p><strong>Note</strong>: Again, this works just the same as expected — have a look at it <a href="https://mdn.github.io/learning-area/javascript/building-blocks/loops/do-while.html">running live on GitHub</a> (also view the <a href="https://github.com/mdn/learning-area/blob/master/javascript/building-blocks/loops/do-while.html">full source code</a>).</p>
</div>

<div class="warning">
<p><strong>Important</strong>: With while and do...while — as with all loops — you must make sure that the initializer is iterated so that it eventually reaches the exit condition. If not, the loop will go on forever, and either the browser will force it to stop, or it wil crash. Thisis called an <strong>infinite loop</strong>.</p>
</div>

<h2 id="Active_learning_Launch_countdown!">Active learning: Launch countdown!</h2>

<p>In this exercise, we want you to print out a simple launch countdown to the output box, from 10 down to Blast off. Specifically, we want you to:</p>

<ul>
 <li>Loop from 10 down to 0. We've provided you with an initializer — <code>var i = 10;</code>.</li>
 <li>For each iteration, create a new paragraph and append it to the output <code>&lt;div&gt;</code>, which we've selected using <code>var output = document.querySelector('.output');</code>. In comments, we've provided you with:
  <ul>
   <li><code>var para = document.createElement('p');</code> — creates a new paragraph.</li>
   <li><code>output.appendChild(para);</code> — appends the paragraph to the output <code>&lt;div&gt;</code>.</li>
   <li><code>para.textContent =</code> — makes the text inside the paragraph equal to whatever you put on the right hand side, after the equals sign.</li>
  </ul>
 </li>
 <li>Different iterations require different text to be put in the paragraph for that iteration:
  <ul>
   <li>If the number is 10, print "Countdown 10" to the paragraph.</li>
   <li>If the number is 0, print "Blast off!" to the paragraph.</li>
   <li>For any other number, print just the number to the paragraph.</li>
  </ul>
 </li>
 <li>Include an iterator! However, in this example we are counting down after each iteration, not up.</li>
</ul>

<p>If you make a mistake, you can always reset the example with the "Reset" button. If you get really stuck, press "Show solution" to see a solution.</p>

<div class="hidden">
<h6 id="Active_learning">Active learning</h6>

<pre class="brush: html">
&lt;div class="output" style="height: 410px;overflow: auto;"&gt;
  
&lt;/div&gt;


&lt;textarea id="code" class="playable-code" style="height: 300px;"&gt;
var output = document.querySelector('.output');
output.innerHTML = '';

// var i = 10;

// var para = document.createElement('p');  
// para.textContent = ;
// output.appendChild(para);
&lt;/textarea&gt;

&lt;div class="playable-buttons"&gt;
  &lt;input id="reset" type="button" value="Reset"&gt;
  &lt;input id="solution" type="button" value="Show solution"&gt;
&lt;/div&gt;
</pre>

<pre class="brush: js">
var textarea = document.getElementById("code");
var reset = document.getElementById("reset");
var solution = document.getElementById("solution");
var code = textarea.value;

function updateCode() {
  eval(textarea.value);
}

reset.addEventListener("click", function() {
  textarea.value = code;
  updateCode();
});

solution.addEventListener("click", function() {
  textarea.value = jsSolution;
  updateCode();
});

var jsSolution = 'var output = document.querySelector(\'.output\');\noutput.innerHTML = \'\';\n\nvar i = 10;\n\nwhile(i &gt;= 0) {\n  var para = document.createElement(\'p\');\n  if(i === 10) {\n    para.textContent = \'Countdown \' + i;\n  } else if(i === 0) {\n   &nbsp;para.textContent = \'Blast off!\';\n  } else {\n    para.textContent = i;\n  }\n\n  output.appendChild(para);\n\n  i--;\n}';

textarea.addEventListener("input", updateCode);
window.addEventListener("load", updateCode);
</pre>
</div>

<p>{{ EmbedLiveSample('Active_learning', '100%', 800) }}</p>

<h2 id="Active_learning_Filling_in_a_guest_list">Active learning: Filling in a guest list</h2>

<p>In this exercise, we want you to take a list of names stored in an array, and put them into a guest list. But it's not quite that easy — we don't want to let Phil and Lola in because they are greedy and rude, and always eat all the food! We have two lists, one for guests to admit, and one for guests to refuse.</p>

<p>Specifically, we want you to:</p>

<ul>
 <li>Write a loop that will iterate from 0 to the length of the <code>people</code> array.</li>
 <li>During each loop iteration, check if the current array item is equal to "Phil" or "Lola":
  <ul>
   <li>If it is, concatenate the array item to the end of the <code>refused</code> paragraph's <code>textContent</code>, followed by a comma and a space.</li>
   <li>If it isn't, concatenate the array item to the end of the <code>admitted</code> paragraph's <code>textContent</code>, followed by a comma and a space.</li>
  </ul>
 </li>
</ul>

<p>We've already provided you with:</p>

<ul>
 <li><code>var i = 0;</code> — An initializer</li>
 <li><code>refused.textContent +=</code> — the beginnings of a line that will concatenate something on to the end of <code>refused.textContent</code>.</li>
 <li><code>admitted.textContent +=</code> — the beginnings of a line that will concatenate something on to the end of <code>admitted.textContent</code>.</li>
</ul>

<p>Extra bonus question — after completing the above tasks successfully, you will be left with two lists of names, separated by commas, but they will be untidy — there will be a comma at the end of each one. Can you work out how to write lines that slice the last comma off in each case, and add a full stop to the end?</p>

<p>If you make a mistake, you can always reset the example with the "Reset" button. If you get really stuck, press "Show solution" to see a solution.</p>

<div class="hidden">
<h6 id="Active_learning_2">Active learning 2</h6>

<pre class="brush: html">
&lt;div class="output" style="height: 150px;overflow: auto;"&gt;
  &lt;p class="admitted"&gt;Admit: &lt;/p&gt;
&nbsp; &lt;p class="refused"&gt;Refuse: &lt;/p&gt;
&lt;/div&gt;

&lt;textarea id="code" class="playable-code" style="height: 400px;"&gt;
var people = ['Chris', 'Anne', 'Colin', 'Terri', 'Phil', 'Lola', 'Sam', 'Kay', 'Bruce'];
    
var admitted = document.querySelector('.admitted');
var refused = document.querySelector('.refused');

// var i = 0;

// refused.textContent += people[i] + ', ';
// admitted.textContent += people[i] + ', ';

&lt;/textarea&gt;

&lt;div class="playable-buttons"&gt;
  &lt;input id="reset" type="button" value="Reset"&gt;
  &lt;input id="solution" type="button" value="Show solution"&gt;
&lt;/div&gt;
</pre>

<pre class="brush: js">
var textarea = document.getElementById("code");
var reset = document.getElementById("reset");
var solution = document.getElementById("solution");
var code = textarea.value;

function updateCode() {
  eval(textarea.value);
}

reset.addEventListener("click", function() {
  textarea.value = code;
  updateCode();
});

solution.addEventListener("click", function() {
  textarea.value = jsSolution;
  updateCode();
});

var jsSolution = 'var people = [\'Chris\', \'Anne\', \'Colin\', \'Terri\', \'Phil\', \'Lola\', \'Sam\', \'Kay\', \'Bruce\'];\n\nvar admitted = document.querySelector(\'.admitted\');\nvar refused = document.querySelector(\'.refused\');\n\nvar i = 0;\n\ndo {\n  if(people[i] === \'Phil\' || people[i] === \'Lola\') {\n    refused.textContent += people[i] + \', \';\n  } else {\n    admitted.textContent += people[i] + \', \';\n  }\n  i++;\n} while(i &lt; people.length);\n\nrefused.textContent = refused.textContent.slice(0,refused.textContent.length-2) + \'.\';\nadmitted.textContent = admitted.textContent.slice(0,admitted.textContent.length-2) + \'.\';';

textarea.addEventListener("input", updateCode);
window.addEventListener("load", updateCode);
</pre>
</div>

<p>{{ EmbedLiveSample('Active_learning_2', '100%', 800) }}</p>

<h2 id="Which_loop_type_should_you_use">Which loop type should you use?</h2>

<p>For basic uses, <code>for</code>, <code>while</code>, and <code>do...while</code> loops are largely interchangeable. They can all be used to solve the same problems, and which one you use will largely depend on your personal preference — which one you find easiest to remember or most intuitive. Let's have a look at them again.</p>

<p>First <code>for</code>:</p>

<pre>
for(initializer; exit-condition; final-expression) {
  // code to run
}</pre>

<p><code>while</code>:</p>

<pre>
initializer
while(exit-condition) {
  // code to run

  final-expression
}</pre>

<p>and finally <code>do...while</code>:</p>

<pre>
initializer
do {
  // code to run

  final-expression
} while(exit-condition)</pre>

<p>We would recommend <code>for</code>, at least to begin with, as it is probably the easiest for remembering everything — the initializer, exit-condition, and final-expression all have to go neatly into the parentheses, so it is easy to see where they are and check that you aren't missing them.</p>

<div class="note">
<p><strong>Note</strong>: There are other loop types/features too, which are useful in advanced/specialized situations and beyond the scope of this article. If you want to go further with your loop learning, read our advanced <a href="/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration">Loops and iteration guide</a>.</p>
</div>

<h2 id="Conclusion">Conclusion</h2>

<p>This article has revealed to you the basic concepts behind, and different options available when, looping code in JavaScript. You should now be clear on why loops are a good mechanism for dealing with repetitive code, and be raring to use them in your own examples!</p>

<p>If there is anything you didn't understand, feel free to read through the article again, or <a href="/en-US/Learn#Contact_us">contact us</a> to ask for help.</p>

<h2 id="See_also">See also</h2>

<ul>
 <li><a href="/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration">Loops and iteration in detail</a></li>
 <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for">for statement reference</a></li>
 <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/while">while</a> and <a href="/en-US/docs/Web/JavaScript/Reference/Statements/do...while">do...while</a> references</li>
 <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/break">break</a> and <a href="/en-US/docs/Web/JavaScript/Reference/Statements/continue">continue</a> references</li>
 <li>
  <p class="entry-title"><a href="https://www.impressivewebs.com/javascript-for-loop/">What’s the Best Way to Write a JavaScript For Loop?</a> — some advanced loop best practices</p>
 </li>
</ul>

<p>{{PreviousMenuNext("Learn/JavaScript/Building_blocks/conditionals","Learn/JavaScript/Building_blocks/Functions", "Learn/JavaScript/Building_blocks")}}</p>
Revert to this revision