JavaScript for Loop

A JavaScript for loop repeats a block of code while a condition remains true. It is commonly used when you know where the loop should start, when it should stop, and how the counter should change after each iteration.

Basic syntax:

for (initialization; condition; update) {
  // code to repeat
}

Simple example:

for (let i = 0; i < 5; i += 1) {
  console.log(i);
}

This prints 0 through 4. The initializer runs once, the condition is checked before each iteration, and the update runs after each completed iteration.

JavaScript for Loop Syntax and Execution Order Top ↑

A classic for statement has three expressions inside the parentheses. They are separated by semicolons.

for (let i = start; i < limit; i += step) {
  // statements to repeat
}

The execution order is: initialization once → condition → loop body → update → condition again. When the condition becomes false, execution continues after the loop.

Important: The condition is checked before the body runs. If it is false on the first check, the loop body runs zero times.

Counting Up with a for Loop Top ↑

The original use case on this page was printing a sequence of numbers. The same idea remains useful, but modern code normally uses let for a loop counter and sends output to the console or DOM instead of document.write().

for (let x = 1; x <= 10; x++) {
  console.log(x);
}

The output is 1 through 10. Using <= 10 includes 10; using < 10 would stop at 9.

Counting Down with a for Loop Top ↑

A loop does not have to increase its counter. Start at a higher value, test with >=, and decrement.

for (let x = 10; x >= 0; x--) {
  console.log(x);
}

This preserves the original countdown example and makes the stopping condition explicit: the final value printed is 0.

Using a Step Greater Than 1 Top ↑

The update expression can change the counter by any amount. To move in steps of 5:

for (let j = 0; j < 100; j += 5) {
  console.log(j);
}

You can also step backward with expressions such as j -= 5.

Looping Through an Array by Index Top ↑

A classic for loop is useful when you need the array index as well as the value.

const colors = ["red", "green", "blue"];

for (let i = 0; i < colors.length; i++) {
  console.log(i, colors[i]);
}

Because array indexes start at 0, the safe test is normally i < colors.length, not i <= colors.length. See the JavaScript array tutorial for array-specific operations.

Using Multiple Variables in a for Loop Top ↑

The initialization and update parts can contain more than one expression separated by commas.

for (let left = 0, right = 4; left < right; left++, right--) {
  console.log(left, right);
}

This can be useful when two counters need to move together, although simpler loops are usually easier to read.

Optional Expressions and Infinite for Loops Top ↑

All three expressions in a classic for statement are optional. If you omit the condition, it behaves as though the condition is always true, so you must provide another way to stop the loop.

let count = 0;

for (;;) {
  if (count === 3) {
    break;
  }
  console.log(count);
  count++;
}
Avoid accidental infinite loops: if the condition can never become false and there is no reachable break, the loop will continue indefinitely and can freeze the page.

Stop a for Loop with break Top ↑

break exits the nearest loop immediately. This modernized version of the original example stops before printing 6.

for (let x = 1; x <= 10; x++) {
  if (x === 6) {
    break;
  }
  console.log(x);
}

The output is 1 2 3 4 5. After break, execution continues with the first statement after the loop.

Skip an Iteration with continue Top ↑

continue does not end the loop. In a classic for loop, it skips the rest of the current body and then proceeds to the update expression.

for (let x = 1; x <= 5; x++) {
  if (x === 3) {
    continue;
  }
  console.log(x);
}

The output is 1 2 4 5. Use continue when one iteration should be ignored but the loop itself should keep running.

Nested for Loops Top ↑

A for loop can contain another loop. The inner loop completes for each iteration of the outer loop.

for (let row = 1; row <= 3; row++) {
  for (let column = 1; column <= 2; column++) {
    console.log(`row ${row}, column ${column}`);
  }
}

Nested loops are common for grids and combinations, but each additional loop can multiply the amount of work. Keep the iteration ranges appropriate for the task.

Labeled break and continue in Nested Loops Top ↑

By default, break and continue affect the innermost loop. JavaScript labels can target an outer loop. This is valid JavaScript, but use it sparingly because deeply nested control flow can become difficult to follow.

outerLoop:
for (let row = 1; row <= 3; row++) {
  for (let column = 1; column <= 3; column++) {
    if (row === 2 && column === 2) {
      break outerLoop;
    }
    console.log(row, column);
  }
}

A labeled continue skips directly to the next iteration of the named outer loop:

outerLoop:
for (let row = 1; row <= 3; row++) {
  for (let column = 1; column <= 3; column++) {
    if (column === 2) {
      continue outerLoop;
    }
    console.log(row, column);
  }
}

let, const and var Inside for Loops Top ↑

Use let for a counter that changes. let is block-scoped, so a counter declared in the loop header is not available after the loop. Older code often uses var; var is function-scoped and can remain accessible outside the loop block.

for (let i = 0; i < 3; i++) {
  console.log(i);
}

// console.log(i); // ReferenceError: i is not defined here

const can be used inside the loop body for values that are newly created on each iteration and do not need reassignment.

Does JavaScript Have a for...else Clause? Top ↑

No. JavaScript does not have Python-style for...else syntax. If you need to know whether a loop completed without finding a match, use a flag or an array method such as find() or some() when that better expresses the task.

const values = [3, 7, 11];
let found = false;

for (let i = 0; i < values.length; i++) {
  if (values[i] === 7) {
    found = true;
    break;
  }
}

if (!found) {
  console.log("Value not found");
}

When to Use for, for...of, forEach or while Top ↑

Use the classic for loop when you need direct control over the counter, step, start/end positions, or break/continue. For iterable values such as arrays, for...of is often clearer when you only need each value.

const colors = ["red", "green", "blue"];

for (const color of colors) {
  console.log(color);
}

forEach() is convenient for running a callback for every array item, but a normal break cannot terminate forEach(). A while loop is often clearer when the number of repetitions depends mainly on a condition rather than a counter.

Do not confuse for...in with for...of: for...in iterates enumerable property names; it is generally not the preferred way to iterate array values.

Common for Loop Mistakes Top ↑

  • Off-by-one conditions: use < versus <= deliberately.
  • Array boundary errors: use i < array.length; array[array.length] is outside the array.
  • Wrong update direction: a counter that moves away from the stopping condition can create an infinite loop.
  • Forgetting the update: if the loop body never changes the state used by the condition, the loop may never end.
  • Using var without understanding scope: prefer let for changing loop counters in modern code.
  • Unnecessary complexity: if you only need array values, for...of may communicate the intent more clearly.

Loops while Loop

Related tutorials: switch statement, JavaScript arrays, PHP for loop, and ASP For...Next loop.

JavaScript Basics




Subscribe to our YouTube Channel here



plus2net.com










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer