Loops are one of the most important control structures in programming, they help us perform repetitive tasks which would be boring and time consuming to do manually in a quick and interesting way. It also helps us handle situations where we want something to continuously happen automatically based on a condition.
There are various types of loops for different purposes, however we'll be exploring the different types of loops in Javascript. In JavaScript, there are several types of loops, some of the common ones and some new specific ones introduced in ES6, they are:
- for loop
- while loop
- do...while loop
- for...in loop
- for...of loop
- for each method
1. For Loop
The for loop repeats a block of code a specified number of times or until a specified condition becomes false. It is similar to the for loop in languages like C, C++ and Java.
It looks like this:
for(initialization; condition; increment){
statement
}
The following occurs when a for loop executes:
i. A variable is initialized (usually 'i' )which serves as a counter to keep track of the number of times a loop occurs.
ii. Every time the loop runs, it checks the condition and stops the loop if the condition is true otherwise it continues.
iii. After that, the counter variable is incremented by 1.
Example:
for (let i = 0; i < 10; i++) {
console.log(i);
}
This loop prints the numbers 0 - 9, for every iteration, it checks if i is less than 10 then prints i if true.
2. While Loop
The while loop executes a block of code as long as a specified condition is true.
It has the following structure:
while(condition)
statement;
The condition test occurs before statement in the loop is executed. If the condition returns true, statement is executed and the condition is tested again. If the condition returns false, execution stops, and control is passed to the statement following while.
Example:
The same program from above using a while loop looks like this:
let i = 0;
while (i < 10) {
console.log(i);
i++;
}
3. Do-While Loop
The do-while loop is similar to the while loop, but it always executes the code block at least once before checking the condition.
The do-while loop looks as follows:
do
statement
while (condition);
The statement is always executed once before the condition is checked. If condition is true, the statement executes again. At the end of every execution, the condition is checked. When the condition is false, execution stops, and control passes to the statement following do...while.
Example:
The same program above in a do-while loop looks like this:
let i = 0;
do {
console.log(i);
i++;
} while (i < 10);
4. For-In Loop (Iterating over Object Properties)
The for-in loop iterates a specified variable over the enumerable properties of an object. i.e over every key-value pair of the object. For each distinct property, JavaScript executes the specified statements.
A for...in statement looks as follows:
for (variable in object)
statement
Example:
const person = {
name: 'John',
age: 30,
city: 'New York'
};
for (let key in person) {
console.log(key + ': ' + person[key])
}
// Output:
name: John,
age: 30,
city: New York
The code above declares an object person and using the for-in loop, iterates over every key and prints out the key and it's value.
NOTE: Using the for-in loop for arrays will return the indexes of the array elements rather than the elements itself. It takes the indexes as the keys and the elements as the values. A better alternative is the for-of loop below.
5. For-Of Loop (Iterating over iterable Objects)
The for-of loop iterates over iterable objects like arrays, strings, maps, sets, etc.
It looks like this:
for (variable of object)
statement
Example:
const fruits = ['apple', 'banana', 'orange'];
for (let fruit of fruits) {
console.log(fruit); // Output: apple, banana, orange
}
Difference between for-in and for-of loops
The following 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:
const arr = [3, 5, 7];
arr.foo = "hello";
for (const i in arr) {
console.log(i);
}
// "0" "1" "2" "foo"
for (const i of arr) {
console.log(i);
}
// Logs: 3 5 7
There you have it, the loops used in Javascript. They have different situations where they are applied. The for-in loop and for-of loops for example make it easier to iterate over arrays and objects easily rather than using the usual for loop which can be sometimes confusing depending on the complexity of the problem you're solving.
Try out all of them and discover what you can achieve with them.
Keep coding ✈️