Loops are utilized to repeatedly execute the same block of code as long as a particular condition remains true. The fundamental concept behind loops is to automate repetitive tasks within a program, thereby saving time and effort. JavaScript currently offers five distinct types of loops:
In the upcoming sections, we will delve into each of these loop types in detail.
This is the most straightforward loop statement offered by JavaScript.
The while
loop executes a block of code as long as the specified condition remains true. Once the condition becomes false, the loop terminates. The general syntax of the while loop is as follows:
The following example demonstrates a loop that continues to run as long as the variable i
is less than or equal to 5. The variable i
increments by 1 each time the loop iterates:
var i = 1;
while(i <= 5) {
document.write("<p>The number is " + i + "</p>");
i++;
}
Note: Ensure that the condition specified in your loop ultimately becomes false. Otherwise, the loop will continue iterating indefinitely, resulting in what's known as an infinite loop. A common mistake is forgetting to increment the counter variable (such as the variable i
in our example).
The do-while
loop is a variation of the while
loop, where the condition is evaluated at the end of each loop iteration. In a do-while
loop, the block of code is executed once, and then the condition is assessed. If the condition is true, the statement is repeatedly executed as long as the specified condition remains true. The general syntax of the do-while loop is as follows:
The JavaScript code in the subsequent example defines a loop that initializes with i=1
. It then prints the output and increments the value of the variable i
by 1. Subsequently, the condition is evaluated, and the loop continues to execute as long as the variable i
is less than or equal to 5.
var i = 1;
do {
document.write("<p>The number is " + i + "</p>");
i++;
}
while(i <= 5);
The while
loop differs from the do-while
loop in a significant way — in a while
loop, the condition is evaluated at the beginning of each loop iteration. Thus, if the conditional expression evaluates to false initially, the loop will not execute at all.
Conversely, in a do-while
loop, the loop is executed at least once, even if the conditional expression evaluates to false. This is because, unlike the while
loop, the condition is evaluated at the end of each iteration rather than the beginning.
The for
loop repeats a block of code as long as a specific condition remains true. It is commonly used to execute a block of code for a predetermined number of times. Its syntax is as follows:
The components of the for
loop statement have the following meanings:
true
, the loop statements execute. If it evaluates to false
, the loop terminates.The following example defines a loop that begins with i=1
. The loop will continue until the value of the variable i
is less than or equal to 5. The variable i
increments by 1 each time the loop runs:
for(var i=1; i<=5; i++) {
document.write("<p>The number is " + i + "</p>");
}
The for
loop is especially handy for iterating over an array. The subsequent example illustrates how to print each item or element of the JavaScript array.
// An array with some elements
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
// Loop through all the elements in the array
for(var i=0; i<fruits.length; i++) {
document.write("<p>" + fruits[i] + "</p>");
}
The for-in
loop is a specialized type of loop designed to iterate over the properties of an object or the elements of an array. The basic syntax of the for-in
loop is:
In the for-in
loop, the loop counter (variable) is a string, not a number. It represents the name of the current property or the index of the current array element.
The following example demonstrates how to iterate through all properties of a JavaScript object.
// An object with some properties
var person = {"name": "Clark", "surname": "Kent", "age": "36"};
// Loop through all the properties in the object
for(var prop in person) {
document.write("<p>" + prop + " = " + person[prop] + "</p>");
}
Similarly, you can iterate through the elements of an array using the for-in
loop, like this:
// An array with some elements
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
// Loop through all the elements in the array
for(var i in fruits) {
document.write("<p>" + fruits[i] + "</p>");
}
strong>Note: It's not recommended to use the for-in
loop for iterating over arrays when the index order matters. It's preferable to use a for
loop with a numeric index instead.
ES6 introduces a new for-of
loop, making iteration over arrays or other iterable objects (such as strings) straightforward. Additionally, the code within the loop executes for each element of the iterable object.
The following example demonstrates how to iterate through arrays and strings using this loop.
// Iterating over array
let letters = ["a", "b", "c", "d", "e", "f"];
for(let letter of letters) {
console.log(letter); // a,b,c,d,e,f
}
// Iterating over string
let greet = "Hello World!";
for(let character of greet) {
console.log(character); // H,e,l,l,o, ,W,o,r,l,d,!
}
To explore other ES6 features, please refer to the JavaScript ES6 features chapter.
Note: The for...of
loop is not compatible with objects because they are not iterable. If you need to iterate over the properties of an object, you should use the for-in
loop.