# JavaScript: Loops, break and continue

September 26, 2018

In this tutorial you’ll learn about loops in JavaScript, one of the most important concepts in programming. In plain English, loop-statements correspond to “Do this action X times.” or “Keep doing that action as long as this condition is true.”

You’ll also learn about two important keywords break and continue. They help in controlling the flow of the program by jumping to statements, skipping certain statements etc.

# for loops

Programmers don’t like to repeat themselves. Programming is all about automating things. Let’s say we have an array of names of people we wish to greet. We can write something like this:

var names = ['Alan', 'Bob', 'Alice'];
console.log("Hello, " + names[0]);
console.log("Hello, " + names[1]);
console.log("Hello, " + names[2]);

Output:

Hello, Alan
Hello, Bob
Hello, Alice

But we don’t want to greet every person by their name manually, right? That’s where loops come in handy.

for (var i = 0; i < names.length; i++) {}

This is a for loop. A for statement behaves the same way as the if statement with a difference that it keeps executing its following code block until the condition remains true. The above statement evaluates to

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

because, names.length is equal to 3.

A for loop has three parts separated by semicolons.

1. Initialization — In our example, the variable i is initialized with value 0.
2. Checking a condition — Then we check if i < 3 is true.
3. Update — If it is true, we execute the following code block and increment i by 1. i++ increments i by 1 and is shorthand for i = i + 1 or i += 1.

The letters i, j, k are generally used for loop variables (it’s kind of a convention).

Let’s see what all values can i take when this loop is executed.

• i = 0; i is less than 3; i is incremented by 1.
• i = 1; i is still less than 3; i is incremented by 1.
• i = 2; i is still less than 3; i is incremented by 1.
• i = 3; i is equal to 3; the condition is false; the loop ends.

So i can take the values 0, 1, 2. We can traverse through our names array using i!

var names = ['Alan', 'Bob', 'Alice'];
for (var i = 0; i < names.length; i++) {
console.log("Hello, " + names[i]);
}

Output:

Hello, Alan
Hello, Bob
Hello, Alice

You can also fill an array with elements using a loop:

var numbers = new Array(100); // creates an empty array with 100 elements
for (var i = 0; i < 100; i++) {
numbers[i] = i + 1; // this will put 1 at index 0, 2 at 1, 3 at 2 and so on.
}
console.log(numbers);

Output:

1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100

This populates the numbers array with natural numbers from 1 to 100.

How to traverse objects?

var obj = {"name": "Commonlounge", "type": "website"};
for (var key in obj) {
console.log(key + ": " + obj[key]);
}

Here, the loop variable is key, and it takes the values "name" and "type".

Output:

name: Commonlounge
type: website

# while loops

In for loops we are certain about the number of times we wish to run the loop. But, what if we aren’t?

Consider, this example. Suppose we want to know how many times a given number can be divided by 2 before it is less than or equal to 1. Yes, we can do the math to figure out the answer, but we are programmers and programmers are lazy. So, we use loops. In this section, we will look at while loops. Before we continue loops, a quick note:

Note: To make things more interesting, from this point on, we will incorporate our Javascript examples in HTML. Don’t worry if you don’t know anything about HTML yet. There are just a couple things to keep in mind:

1. We will use document.write() function, instead of console.log to print out the values we care about. document.write is a special function that lets us write to the HTML document.
2. We will use prompt() function to capture the input from the user.

For example, to take the number as input from the user. Remember the prompt function?

var i = prompt("Enter a number");

That’s it.

Coming back to loops. For a while loop, we initialize the loop variable outside the loop, unlike the for loop. Here, our loop variable is the number itself, because we are going to divide it by 2 in every loop iteration.

As we say above, the structure of a while loop is simple:

while (<condition is true>) {
// codeblock
}

We want to know the number of times the given number can be divided by 2, so we make another variable called counter, which stores the answer.

Are you excited to try your first while loop? Hit the Try it now button below and see what happens!

<html>
<script>
var i = prompt("Enter a number");
var counter = 0;
while (i > 1) {
i /= 2; // same as i = i / 2
counter++;
document.write("Number is " + i + " after " + counter + " divisions", "<br>");
}
document.write("Answer = " + counter, "<br>");
</script>
</html>

If you give input 10, you will see the following output:

Number is 5 after 1 divisions
Number is 2.5 after 2 divisions
Number is 1.25 after 3 divisions
Number is 0.625 after 4 divisions
Answer = 4

Did you notice the operator /= in line 7 of the code? This is called an augmented assignment. It is equivalent to

i = i / 2;

Similar to this, we have

i += 2;  // same as i = i + 2
i -= 2;  // same as i = i - 2
i *= 2;  // same as i = i * 2
i %= 2;  // same as i = i % 2
i **= 2; // same as i = i ** 2

etc., every operator can be used as described above.

# Writing a while loop as a for loop

You can always convert a while loop to for loop and vice-versa. For example, the while loop example we saw can be converted to a for loop as follows:

<html>
<script>
var i = prompt("Enter a number");
var counter = 0;
for (; i > 1; i /= 2) {
counter++;
}
document.write("Answer = " + counter, "<br>");
</script>
</html>

Notice, that since we have already initialized the loop variable outside of the loop, we do not need to do it again inside the loop (if we do, it will change the value of i to the value we set inside the loop).

We can also write this as:

<html>
<script>
var counter = 0;
for (var i = prompt("Enter a number"); i > 1; i /= 2) {
counter++;
}
document.write("Answer = " + counter, "<br>");
</script>
</html>

This resembles more with the structure we discussed first.

# Exercise: Writing a for loop as a while loop

Convert the for-loop in the following code into a while-loop:

<html>
<script>
var numbers = [1, 2, 3, 4, 5, 6];
for (var i = 0; i < numbers.length; i++) {
var square = numbers[i] * numbers[i];
document.write("The square of " + numbers[i] + " is " + square, "<br>");
}
</script>
</html>

Please try the exercise above yourself, before looking at the solution below!

<html>
<script>
var numbers = [1, 2, 3, 4, 5, 6];
var i = 0
while (i < numbers.length) {
var square = numbers[i] * numbers[i];
document.write("The square of " + numbers[i] + " is " + square, "<br>");
i++;
}
</script>
</html>

# Break and continue

break and continue give us some more control over what code is executed inside a loop.

If a break is encountered, JavaScript immediately stops iterating over the loop (it also ignores all the code after the break within the block, if any). Here’s an example; save the following code in "loops.html":

<html>
<script>
var a = [1, 5, 3, 2, 4, 6];
for (var i = 0; i < a.length; i++) {
document.write(a[i], "<br>");
if (a[i] === 2)
break;                      // quit the loop when a[i] === 2
document.write(-a[i], "<br>");  // when element === 2, this line too won't execute
}
</script>
</html> 

Here’s the code output:

1
-1
5
-5
3
-3
2

Note: 4 and 6 don’t get printed at all. 2 gets printed, but -2 does not, since break happens before that.

If a continue is encountered, JavaScript ignores the code after the continue within the block, but “continues” iterating over the rest of the elements. Here’s an example:

<html>
<script>
var a = [1, 5, 3, 2, 4, 6];
for (var i = 0; i < a.length; i++) {
document.write(a[i], "<br>");
if (a[i] <= 2)
continue;                   // don't execute the rest if element <= 2
document.write(-a[i], "<br>");  // when element <= 2, this line too won't execute
}
</script>
</html>

Here’s the code output:

1
5
-5
3
-3
2
4
-4
6
-6

Note: All numbers get printed. However, for 1 and 2, the negative values don’t get printed because of the continue.

Lastly, break and continue can be used inside while-loops as well.

# Summary

In the last few exercises you learned about:

• loops – you learnt two types of loops, the for-loop and the while-loop
• break and continuebreak can be used to exit the loop, and continue can be used to skip some parts of the loop body

Quiz time!