Skip to main content

Archive

Show more

JavaScript For Loop

JavaScript For Loop

The for loop in JavaScript is a fundamental control structure that allows you to execute a block of code repeatedly, based on a specified condition. It is often used when the number of iterations is known beforehand, such as when iterating over arrays or performing operations a fixed number of times.


Basic Syntax of the for Loop

The for loop consists of three main parts:

  1. Initialization: Sets the initial value of the loop control variable.
  2. Condition: Checks whether the loop should continue executing.
  3. Increment/Decrement: Updates the loop control variable after each iteration.
for (initialization; condition; increment/decrement) {
  // Code to be executed in each iteration
}

All three components are optional, but the semicolons ; must always be included.


Example: Counting Numbers

Here's a simple example of a for loop that counts from 1 to 5:

for (let i = 1; i <= 5; i++) {
  console.log(i);
}
// Output: 1 2 3 4 5
  • let i = 1; initializes the loop control variable i to 1.
  • The condition i <= 5 checks if i is less than or equal to 5. If true, the loop executes.
  • i++ increments i by 1 after each iteration.

Using the for Loop to Iterate Over Arrays

The for loop is commonly used to iterate over the elements of an array:

const fruits = ['apple', 'banana', 'cherry'];

for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}
// Output: apple banana cherry

Here, the loop runs from i = 0 to i < fruits.length, printing each fruit in the array.


Example: Decrementing in a for Loop

You can also use a for loop to decrement a value:

for (let i = 5; i > 0; i--) {
  console.log(i);
}
// Output: 5 4 3 2 1

This loop starts with i = 5 and decrements until i is greater than 0.


Skipping Iterations Using continue

The continue statement can be used to skip the current iteration and proceed to the next:

for (let i = 1; i <= 5; i++) {
  if (i === 3) {
    continue; // Skip the iteration when i equals 3
  }
  console.log(i);
}
// Output: 1 2 4 5

In this example, the loop skips the iteration when i === 3.


Breaking Out of a for Loop

The break statement terminates the loop immediately:

for (let i = 1; i <= 5; i++) {
  if (i === 4) {
    break; // Exit the loop when i equals 4
  }
  console.log(i);
}
// Output: 1 2 3

Here, the loop stops executing when i === 4.


Infinite for Loop

An infinite loop occurs when the condition is always true:

for (;;) {
  console.log('This is an infinite loop.');
}
// This loop will run forever unless stopped manually.

Be cautious when writing loops to avoid creating infinite loops unintentionally.


Conclusion

The for loop is a versatile and powerful tool for performing repetitive tasks in JavaScript. Whether iterating over arrays, counting numbers, or controlling execution flow, understanding the for loop is essential for effective programming.

Comments