An Introduction to Basic JavaScript Loops
Odhiambo Ouko
Posted on May 29, 2024
Introduction
As a frontend and/or JavaScript developer, there are multiple occasions when we will want our code to conduct repetitive tasks. We can achieve this by writing the code manually a couple of times, but this process can be tedious, especially when we have a handful of code blocks to execute repeatedly. Thankfully, we can use loops in JavaScript to execute a block code several times. In this article, we will discuss the for, do, and while loops, with a focus on their syntax and examples.
What are Loops in JavaScript?
In JavaScript, loops are powerful tools designed to perform repetitive tasks quickly and efficiently. A loop executes a code block several times depending on a specified condition, commonly known as the stopping condition. The code will run over and over again until the condition returns false.
Types of Loops
There are three main types of loops in JavaScript: for, while, and do…while loops. While both loops can iterate a code block several times, the loop types work differently and are suitable for different scenarios.
1. For Loop
The for loop is a control flow statement that examines a condition and executes a code several times as long as the condition is true. We often use the for loop if we need to run a code block a specific number of times. For this reason, the condition in a for loop is usually a counter indicating how many times the loop should run a code. Besides, the for loop is the most common loop in JavaScript and other high-level programming languages.
For Loop Syntax
for (initialization; condition; iteration statement) {
//code block to be executed
}
The code above represents the syntax of a basic for loop. It starts with the for keyword, then the initialization, condition, and iteration statements enclosed in parentheses, followed by the code to be executed in curly brackets (loop body). Let us dissect each part in the parentheses to understand what they are and their uses.
- Initialization: The initialization, commonly abbreviated as
i
, initializes a loop and determines how the loop iterates through your logic. It's executed first and once in a loop. Since the initialization expression is a variable, we can use thelet
orvar
keyword to declare it.
Condition: A condition is the second recipe in a for-loop statement. The condition is usually a Boolean function that tells the loop how many times it should run a code block. A loop will run if the condition is true and stop when the condition is false.
Iteration Statement: Once the loop has executed a code block, the iteration statement will tell it what to do with the iterator. In most cases, the iteration statement can increase or decrease the iterator.
For Loop in Action
Example 1
for (let i = 1; i < 11; i++) {
console.log(i);
}
Output
1
2
3
4
5
6
7
8
9
10
Example 2
for (let i = 10; i > 0 ; i--) {
console.log(i);
}
Output
10
9
8
7
6
5
4
3
2
1
Example 3
const luxuryBrands = ['Chanel', 'Prada', 'Dior', 'Rolex'];
for (let i = 0; i < luxuryBrands.length; i++) {
console.log(luxuryBrands[i]);
}
Output
Chanel
Prada
Dior
Rolex
Example 4
const number = 50;
let totalSum = 0;
for (i = 0; i <= number; i++) {
totalSum = totalSum + i;
}
console.log(totalSum)
Output
1275
2. While Loop
We can use the while loop if we're unsure how many times we should iterate a line of code. Unlike the for loop, the condition for a while loop can be anything other than a counter. A while loop will execute the code in its body repeatedly, provided the condition is true.
Figure 2: While loop flowchart
While Loop Syntax
while (condition) {
//code block to be executed
}
The standard syntax of a while loop is as shown above. It begins with the while statement followed by the condition in parentheses. The code block we want to run comes after the parentheses. In a while loop, the condition is examined before the loop body. As a result, the loop will not run the code block if the condition is false. It will only execute the code if the condition is initially true and terminate when it becomes false. Thus, the while loop is excellent for scenarios where the condition is true at the outset.
While Loop in Action
Example 1
let i = 1;
while (i < 10) {
console.log(i)
i++;
}
Output
1
2
3
4
5
6
7
8
9
3. Do…While Loop
The do…while loop is similar to the while loop since it is effective for running a code if the number of iterations is undefined. Below is a simple syntax of the do…while loop.
Figure 3: Do…While Loop Flowchart
Do...While Loop Syntax
do {
//code block to be executed
} while(condition)
The loop starts with the do keyword, a code block to be executed within curly brackets, the while keyword, and the condition to be evaluated in parenthesis. Since the do keyword comes before the loop body, the code in the curly brackets must run at least once, even if the condition is false. That's because the do…while loop evaluates the condition after the code block, unlike in the while loop.
Do…While Loop in Action
Example 1
let num = 10;
do {
console.log(num);
num++;
} while (num <= 50);
Output
10
20
30
40
50
Closing Thoughts
In this article, we've learned that a loop is a powerful JavaScript tool used for iterating through code blocks. Instead of writing repetitive code manually, the for, while, and do…while loops allow you to iterate through a block of code with less effort. Knowing when to use each type of loop and avoid common pitfalls is crucial in maximizing their potential.
Posted on May 29, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.