Loops are an essential aspect of programming, and in JavaScript, they allow you to execute a block of code repeatedly. Whether you need to process items in an array, iterate over the properties of an object, or perform a task a specific number of times, loops provide the necessary functionality. This article explores the different types of loops available in JavaScript, along with loop control statements, and provide code examples and explanations to help you grasp the concepts.
The for Loop
The for loop is one of the most commonly used looping constructs in JavaScript. It allows you to iterate over a sequence of values or perform a set number of iterations.
Let’s see an example that prints numbers 1 through 10 using the for loop:
for (let i = 1; i <= 10; i++) {
// Print the current value of i to the console
console.log(i);
}
The for loop has three parts separated by semicolons. Initialization (let i = 1) sets the initial value of the loop counter,
condition (i <= 10) specifies the condition that must be true for the loop to continue executing, and finally, increment (i++) updates the loop counter after each iteration.
The loop will execute as long as the condition (i <= 10) is true. In each iteration, the loop counter (i) is printed to the console.
The while Loop
The while loop executes a block of code as long as a specified condition remains true. It is useful when the number of iterations is not known in advance.
Let’s see an example that prints numbers 1 through 10 using the while loop:
let i = 1;
while (i <= 10) {
// Print the current value of i to the console
console.log(i);
// Add 1 to i
i++;
}
The loop starts with an initial value of 1. The condition (i <= 10) is checked before each iteration. The loop continues executing as long as the condition remains true. Within the loop, the current value of i is logged to the console, and i is incremented by 1.
The do while Loop
Similar to the while loop, the do while loop executes a block of code as long as a specified condition remains true. The difference is that the condition is checked after each iteration. Hence, it’s guaranteed to run at least once.
Let’s see an example that prints numbers 1 through 10 using the do while loop:
let i = 1;
do {
// Print the current value of i to the console
console.log(i);
// Add 1 to i
i++;
} while (i <= 10);
The loop executes the code block once before checking the condition. As long as i is less than or equal to 10, the loop will continue executing. The loop counter is logged to the console in each iteration.
The for-in Loop
The for-in loop is used to iterate over the properties of an object. It allows you to access each property key.
const person = {
name: "Edward Stephen Jr.",
age: 28,
city: "Lusaka",
country: "Zambia",
language: "JavaScript",
level: "Intermediate"
};
for (let key in person) {
// Print key and it's corresponding value
console.log(key + ": " + person[key]);
}
The for-in loop iterates over the properties (key) of the person object. For each iteration, the key and its corresponding value are printed to the console. Used on arrays, the indices of the array act as the keys.
Let’s see an example that prints elements of an array using the for-in loop:
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (let index in numbers) {
// Print element at position index
console.log(numbers[index]);
}
The for-in loop successfully iterates over the array numbers, and the console.log statement prints each element in the array sequentially. However, it’s important to note that the for-in loop is generally better suited for iterating over object properties, and for arrays, it’s recommended to use the for-of loop for more straightforward and predictable iteration. The for-of loop directly iterates over the array elements without the need for accessing indices.
The for-of Loop
Introduced in ECMAScript 6, the for-of loop provides an easy way to iterate over iterable objects such as arrays and strings.
const languages = ["C", "Dart", "JavaScript", "Swift"];
for (let language of languages) {
// Print language to the console
console.log(language);
}
The for-of loop iterates over each element of the languages array. In each iteration, the current element is logged to the console.
Loop Control Statements
JavaScript provides loop control statements to manipulate the flow of loops. Let’s explore two commonly used control statements.
The break Statement
The break statement allows you to exit a loop prematurely, terminating its execution.
for (let i = 1; i <= 10; i++) {
if (i === 5) {
// Exit loop
break;
}
console.log(i);
}
The loop will terminate when i equals 5. The break statement immediately exits the loop, and the code execution continues outside the loop.
The continue statement
The continue statement skips the current iteration and moves to the next iteration of the loop.
for (let i = 1; i <= 10; i++) {
if (i === 2) {
// Move to next iteration
continue;
}
console.log(i);
}
When i equals 2, the continue statement is encountered. It skips the current iteration and moves to the next iteration without executing the remaining code within the loop. The value of i is logged to the console for every other iteration.
Conclusion
Loops are fundamental constructs in JavaScript that allow you to repeat code execution and iterate over collections. The for, while, do while, for-in, and for-of loops offer flexibility and cater to different looping requirements. Additionally, the break and continue statements provide control over the loop’s flow. By mastering these looping mechanisms, you can tackle a wide range of programming tasks effectively and efficiently in JavaScript.
Sources
I hope you found this information informative. If you would like to receive more content, please consider subscribing to our newsletter!