A for
loop provides a concise way to write a loop structure. It repeatedly executes a block of code as long as a specified condition is true, making it ideal for iterating a set number of times.
Example 1: Simple Counter
// This for loop will count from 1 to 5.
for (let i = 1; i <= 5; i++) {
console.log('Count:', i);
}
Explanation This code initializes a counter i
at 1. The loop will continue to run as long as i
is less than or equal to 5, and i
increases by 1 after each iteration.
Example 2: Iterating Over an Array
// Using a for loop to access each element in an array.
const colors = ['Red', 'Green', 'Blue', 'Yellow'];
for (let i = 0; i < colors.length; i++) {
console.log('Color:', colors[i]);
}
Explanation This loop iterates through the colors
array. The loop starts at index 0 and runs as long as the counter i
is less than the total number of elements in the array.
Example 3: Finding a Value in an Array
// A for loop to find a specific item in an array.
const numbers = [10, 20, 30, 40, 50];
const target = 30;
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] === target) {
console.log('Found', target, 'at index', i);
break; // Exit the loop once the value is found.
}
}
Explanation This loop searches for the target
value within the numbers
array. If the target
is found, it prints the index and the break
statement terminates the loop to improve efficiency.
Example 4: Reverse Iteration
// A for loop that counts down from 5 to 1.
for (let i = 5; i > 0; i--) {
console.log('Countdown:', i);
}
Explanation This demonstrates a for
loop that decrements. It initializes i
to 5 and continues as long as i
is greater than 0, decreasing i
by 1 in each step.
Example 5: Skipping Iterations with continue
// This loop will print all numbers from 1 to 10 except for 5.
for (let i = 1; i <= 10; i++) {
if (i === 5) {
continue; // Skip the current iteration.
}
console.log('Number:', i);
}
Explanation The continue
statement is used to skip the current iteration of the loop when i
is equal to 5 and proceed to the next iteration.
Example 6: Nested For Loops
// Using a nested for loop to create a simple 2D grid.
for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
console.log(`Row ${i}, Column ${j}`);
}
}
Explanation This code contains a loop inside another loop. The outer loop handles the rows, and the inner loop handles the columns, resulting in a 3x3 grid representation.
Example 7: Calculating the Sum of an Array
// A for loop to calculate the sum of all numbers in an array.
const values = [1, 2, 3, 4, 5];
let sum = 0;
for (let i = 0; i < values.length; i++) {
sum += values[i]; // Add each value to the sum.
}
console.log('The total sum is:', sum);
Explanation This loop iterates through the values
array, and in each iteration, it adds the current element to the sum
variable, effectively calculating the total.