HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Loop For

Loops can execute a block of code a number of times. They are perfect for situations where you need to run the same code over and over again, each time with a different value.


The For Loop Syntax

The for loop has three optional expressions, separated by semicolons:

for (expression 1; expression 2; expression 3) {
  // code block to be executed
}

The Three Expressions

  • Expression 1 is executed (one time) before the starting of the code block. Generally used to initialize the counter variable.
  • Expression 2 defines the condition for executing the code block. If it returns true, the loop starts over; if it returns false, the loop ends.
  • Expression 3 is executed (every time) after the code block has been executed. Generally used to increment the counter.

Basic Example

A simple loop that counts from 0 to 4:

for (let i = 0; i < 5; i++) {
  console.log("The number is " + i);
}

Looping Through an Array

For loops are most commonly used to iterate over arrays.

const cars = ["BMW", "Volvo", "Saab", "Ford"];

for (let i = 0; i < cars.length; i++) {
  console.log(cars[i]);
}
Tip: Always use let to declare your counter variable (like i). This ensures the variable is only available inside the loop's block scope.

Skipping Expressions

Expressions in a for loop are optional. For example, you can omit the first expression if your values are already set:

let i = 2;
let len = cars.length;
for (; i < len; i++) {
  text += cars[i];
}

Key Points to Remember

  • Loops save time and reduce code redundancy
  • The for loop is the most versatile looping structure
  • All three expressions are optional, but semicolons are required
  • Block scope (using let) is the best practice for loop counters
  • The condition is checked before every iteration
  • The increment/decrement happens after the code block runs