JavaScript Loops Explained
Richard Rembert
Posted on September 14, 2022
In JavaScript, we use loops when we want an easy way to handle repetition. In this article, we’re going to take a look at all the different ways we can create loops in our code — and we’ll consider the pros and cons of each method.
A way to think of a loop could be to think of giving commands to a robot. You could tell it to take 10 steps — and rather than issuing 10 separate commands, we can create a loop:
let i;
for (i = 0; i < 10; i++) {
document.write("Take one step!\n");
}
This is an example of a for
loop. At first, this may be confusing — but we’ll break it all down in the next section! In this article, we’ll be reviewing many different kinds of loop statements, such as: for
, do...while
, while
, labelled statement
, break statement
, continue statement
, for...in
& for...of
. It’s worth noting that despite their differences in syntax — loops all essentially do the same thing: repeat an action a number of times. The situation dictates which type of loop is best suited.
the for loop
As we’ve seen in the above example, a for
loop will repeat until our condition evaluates to false. The logical structure is like so:
for ([initialExpression]; [condition]; [incrementExpression])
statement
We are first initializing the initialExpression
, which usually initializes one or more loop counters, but the syntax even allows for more complex expressions such as variables. We next evaluate our condition
, if true, the loop statements will execute. If false, the loop terminates.
Then the statement
executes. When we wish to execute multiple statements, we use a block statement ({ ... }
) to group them together. If present, the update expression incrementExpression
is executed. Control then returns to evaluating the condition
.
Let’s now return to our previous example:
let i;
for (i = 0; i < 10; i++) {
document.write("Take one step!\n");
}
Here we can see our for
statement is counting the number of steps taken up to 10. The variable i
will ensure we’re starting from the beginning by initializing to zero. Then it will check that i
is less than the number we specify, which in our case is 10. The i++
is the count which will increment i
by 1 after each pass through the loop. So our loop knows when to complete!
do...while statement
A do...whilestatement
will repeat until the condition evaluates to false. The structure is like so:
do
statement
while (condition);
It’s fairly self-explanatory, statement
is always executed once prior to the condition being checked. And then again until the while condition returns false. We can execute multiple statements, using a block statement ({ ... }
) to group them. If condition
is true, the statement executes again. At the end of each execution, the condition is checked. When the condition returns false, the execution stops and control passes to the statement which follows do...while
.
Let’s see an example:
let i = 0;
do {
i += 1;
console.log(i);
} while (i < 10);
Here our do
loop iterates at least once and then reiterates until i
is no longer less than 10.
while statement
A while
statement executes its statements as long as a specified condition evaluates to true. Its syntax is as follows:
while (condition)
statement
If the condition becomes false, the statement
within the loop stops executing and control then passes to the statement following the loop.
The condition test occurs before the statement
in the loop is executed. And if the condition returns true, the statement
is executed and the condition is tested again. If the condition returns false, execution will stop and control is passed to the statement following while
.
And as with do...while
, we can execute multiple statements using a block statement ({ … }) to group them together.
The following while
loop will iterate as long as a
is less than three:
let a = 0;
let b = 0;
while (a < 3) {
a++;
b+= a;
}
Here with each iteration, the loop increments a
and adds that value to b
. Therefore, a
and b
take on the following values:
- After the first pass through the loop :
a
= 1 andb
= 1 - And the second pass:
a
= 2 andb
= 3 - And the third pass:
a
= 3 andb
= 6
After completion of the third pass, the condition a < 3
is no longer true, so that’s where our loop terminates!
Note: When you first start working with loops, you may accidentally create an infinite loop. This is when a loop condition never evaluates to false. The statements in the following while
loop execute forever because the condition is never false:
while (true) {
console.log('Hi there!');
}
CAUTION: If you run this code — please be aware that it’s likely to crash your browser!! So make sure you’ve backed up your open tabs - if you want to see what happens.
labelled statement
You can attach a label
to any statement to serve as an identifier so you can refer to it elsewhere in your program. As an example, you could use a label to identify a loop, and then use break
or continue
statements to indicate whether a program should interrupt the loop, or continue its execution (we’ll take a look at these below).
label :
statement
he value of label
may be anything you like (with the exception of a JavaScript reserved word). Then you provide the statement
to execute.
So for example, you could use the label totalLoop
to identify a while
loop.
totalLoop:
while (total == true) {
doSomething();
}
break statement
We use the break
statement to terminate a loop or switch
, or in conjunction with a labelled statement.
- When you use
break
without a label, it terminates the innermost enclosingwhile
,do-while
,for
, orswitch
immediately and transfers control to the following statement. - When you use
break
with a label, it terminates the specified labelled statement.
A break
statement looks like this:
break [label];
For example, let’s loop through an array until we find the index of an element with the value of: foundMe
for (let i = 0; i < a.length; i++) {
if (a[i] == foundMe) {
break;
}
}
And let’s use break with a labelled statement:
let x = 0;
let z = 0;
endLoops: while (true) {
console.log('Outer loops: ' + x);
x += 1;
z = 1;
while (true) {
console.log('Inner loops: ' + z);
z += 1;
if (z === 10 && x === 10) {
break endLoops;
} else if (z === 10) {
break;
}
}
}
continue statement
We use the continue
statement to restart a while
, do-while
, for
, or label
statement.
When you use continue
without a label, it terminates the current iteration of the innermost enclosing while
, do-while
, or for
statement and continues execution of the loop with the next iteration. This contrasts with the break
statement, as continue
doesn’t terminate the execution of the loop entirely. In a while
loop, it jumps back to the condition. In a for
loop, it jumps to the initial-expression
.
When you use continue
with a label, it applies to the looping statement identified with that label.
A continue
statement looks like so:
continue [label];
For example, the following code block shows a while
loop with a continue
statement that will execute when the value of i
is three. So n
takes on the values one, three, seven, and twelve.
let i = 0;
let n = 0;
while (i < 5) {
i++;
if (i == 3) {
continue;
}
n += i;
console.log(n);
}
// 1,3,7,12
let i = 0;
let n = 0;
while (i < 5) {
i++;
if (i == 3) {
// continue;
}
n += i;
console.log(n);
}
// 1,3,6,10,15
for...in statement
A for...in
statement iterates a specified variable over all the enumerable properties of an object. For each distinct property, JavaScript executes the specified statements. The syntax is as follows:
for (variable in object) {
statements
}
The following function takes as its argument an object and the object’s name. It then iterates over all the object’s properties and returns a string that lists the property names and their values.
function get_names(obj, obj_name) {
let result = '';
for (let i in obj) {
result += obj_name + '.' + i + ' = ' + obj[i] + '<br>';
}
result += '<hr>';
return result;
}
For an object food
with properties lunch
and dinner
, result
would be:
food.lunch = Sandwich
food.dinner = Lasagna
Note: Given that for...in
is built for iterating object properties, it's not recommended for use with arrays — where the index order is important. For arrays, it’s better to use the more traditional for
loop.
for...of statement
A for … of
statement creates a loop that iterates over iterable objects, such as Array
, Map
, Set
, arguments
and so on. The syntax is like so:
for (variable of object) {
statement
}
The below example shows the difference between a for...of
loop and a for … in
loop. While for...in
iterates over property names, for...of
iterates over property values:
let arr = [10, 20, 30];
arr.greet = 'hello';
for (let i in arr) {
console.log(i); // logs "0", "1", "2", "greet"
}
for (let i of arr) {
console.log(i); // logs 10, 20, 30
}
Summary
We’ve learned about many of the different loop statements, such as: for
, do...while
, while
, labeled statement
, break statement
, continue statement
, for..in
& for...of
. And we’ve looked at a number of examples highlighting ideal use cases for each type of loop. Whichever statements we choose to utilize, we’re now well equipped to add logic and reasoning to our programs.
Conclusion
If you liked this blog post, follow me on Twitter where I post daily about Tech related things!
If you enjoyed this article & would like to leave a tip — click here
🌎 Let's Connect
Posted on September 14, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.