Looping Magic in JavaScript
Loops are fundamental in programming for repeating a block of code multiple times. JavaScript provides several looping mechanisms, each with its use cases. This article covers different ways to loop through data in JavaScript, including for
, while
, do...while
, for...in
, and for...of
.
For Loop
The for
loop is one of the most commonly used loops. It repeats a block of code a specified number of times. The syntax includes an initialization, condition, and increment expression.
// Example: Looping from 0 to 4
for (let i = 0; i < 5; i++) {
console.log(i);
}
// Output: 0, 1, 2, 3, 4
let i = 0
initializes the loop counter.i < 5
is the condition that keeps the loop running while true.i++
increments the counter after each iteration.
While Loop
The while
loop executes a block of code as long as a specified condition is true. It is useful when the number of iterations is not known beforehand.
// Example: Looping until a condition is met
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
// Output: 0, 1, 2, 3, 4
let i = 0
initializes the counter.i < 5
is the condition for the loop to continue.i++
increments the counter inside the loop.
Do…While Loop
The do...while
loop executes a block of code once before checking the condition and then repeats the loop as long as the condition is true. This guarantees that the loop code runs at least once.
// Example: Looping until a condition is met
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
// Output: 0, 1, 2, 3, 4
let i = 0
initializes the counter.- The block of code is executed before checking
i < 5
. i++
increments the counter inside the loop.
Support Our Work: BuyMeACoffee
Originally published at https://www.rustcodeweb.com on August 15, 2024.