JavaScript Loops
JavaScript loops are a fundamental concept in programming, allowing you to execute a block of code multiple times based on a given condition. They are essential for tasks that require repeated actions, such as iterating over arrays, processing data, or automating repetitive tasks.
Types of Loops in JavaScript
1. for Loop
for LoopThe for loop is commonly used for iterating over a block of code a specific number of times. It consists of three parts: initialization, condition, and increment/decrement.
for (initialization; condition; increment/decrement) {
// Code to be executed
}
Example:
for (let i = 0; i < 5; i++) {
console.log(i); // Outputs 0, 1, 2, 3, 4
}
2. while Loop
The while loop executes a block of code as long as the specified condition is true.
while (condition) {
// Code to be executed
}
Example:
let i = 0;
while (i < 5) {
console.log(i); // Outputs 0, 1, 2, 3, 4
i++;
}
3. do...while Loop
The do...while loop is similar to the while loop, but it ensures that the code block is executed at least once before checking the condition.
do {
// Code to be executed
} while (condition);
Example:
let i = 0;
do {
console.log(i); // Outputs 0, 1, 2, 3, 4
i++;
} while (i < 5);
4. for...in Loop
The for...in loop is used to iterate over the properties of an object.
for (variable in object) {
// Code to be executed
}
Example:
const person = {name: 'John', age: 30, city: 'New York'};
for (let key in person) {
console.log(key + ': ' + person[key]); // Outputs name: John, age: 30, city: New York
}
5. for...of Loop
The for...of loop is used to iterate over the values of an iterable object (like an array or a string).
for (variable of iterable) {
// Code to be executed
}
Example:
const numbers = [1, 2, 3, 4, 5];
for (let num of numbers) {
console.log(num); // Outputs 1, 2, 3, 4, 5
}
Loop Control Statements
1. break
breakThe break statement terminates the loop immediately and transfers control to the code following the loop.
for (let i = 0; i < 10; i++) {
if (i === 5) {
break;
}
console.log(i); // Outputs 0, 1, 2, 3, 4
}
2. continue
The continue statement skips the current iteration of the loop and proceeds with the next iteration.
for (let i = 0; i < 10; i++) {
if (i === 5) {
continue;
}
console.log(i); // Outputs 0, 1, 2, 3, 4, 6, 7, 8, 9
}