What is the for Loop?
The for
loop is used to execute a block of code a specific number of times. It is commonly used for iterating over arrays or executing code repeatedly based on a condition.
The for
loop is used to execute a block of code a specific number of times. It is commonly used for iterating over arrays or executing code repeatedly based on a condition.
for (initialization; condition; increment) {
// Code to execute
}
for (let i = 0; i < 5; i++) {
console.log('Iteration: ' + i);
}
Output:
Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
const fruits = ['apple', 'banana', 'cherry'];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
Output:
apple
banana
cherry
let sum = 0;
for (let i = 1; i <= 10; i++) {
sum += i;
}
console.log('Sum: ' + sum);
Output:
Sum: 55
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 2; j++) {
console.log('i: ' + i + ', j: ' + j);
}
}
Output:
i: 0, j: 0
i: 0, j: 1
i: 1, j: 0
i: 1, j: 1
i: 2, j: 0
i: 2, j: 1
The for
loop is ideal for scenarios where you know the number of iterations in advance, such as processing arrays or executing a block of code a fixed number of times.
The for
loop is a fundamental control structure in JavaScript that allows you to efficiently repeat code. Understanding how to use it effectively can enhance your coding skills.