1. javascript
  2. /references
  3. /for-loop

The For Loop in JavaScript

The for loop is the cornerstone of JavaScript traditional loops. It gives a straightforward way to repeat a series of statements a designated number of times.

It can be used for a range of tasks, including iterating over arrays and other iterable objects, performing calculations and computations, modifying and transforming data, implementing conditional logic, and generating sequences and patterns.

The for loop header consists of three optional expressions:

for (initialization; condition; increment/decrement) {
  // the body of the loop
}
  • Initialization: sets the starting value for the loop

  • The condition: determines when the loop should stop

  • Final expression: updates the value after each iteration

The For Loop Over an Iterable Object

In JavaScript, we can use the for loop over iterable objects, such as arrays.

For instance, we can go through an array and print each element as so:

const pizza = ["Neapolitan", "Sicilian", "Roman"];

for (let i = 0; i < pizza.length; i++) {
  console.log(arr[i]);
}
// Output:
// Neapolitan
// Sicilian
// Roman

A Nested For Loop

Nested for loops allow you to perform a set of operations on a nested array or data structure.

Here's how we can flatten a nested array:

const nestedArr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
const flatArr = [];

for (let i = 0; i < nestedArr.length; i++) {
  for (let j = 0; j < nestedArr[i].length; j++) {
    flatArr.push(nestedArr[i][j]);
  }
}

console.log(flatArr); // Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

The For Loop Expressions

In the for loop header, the expressions are optional, and we can omit any of these expressions by providing a semicolon in their place.

Potentially, we can even create a for loop without a body, but it's generally better to use a while loop in these cases.

let i = 0;

for (;;) {
  // statements and logging
}

Now, this is a more common occurrence where we can remove the declaration of the variable:

let i = 0; // Variable declared outside of the loop

// Initialization
for (; i < 5; i++);
console.log(i);
// Output: 5

Similarly, we can omit the condition, but in that case, we should use the break statement to avoid an infinite loop:

for (let i = 0; ; i++) {
  console.log(i);
  if (i > 7) break;
}

Further Learning

Frequently Asked Questions about the JavaScript For Loop

1. How do you loop through the elements in an array?

Yes, a for loop can be used to iterate over the properties of an object as well as the elements of an array. In fact, the for-in loop is specifically designed to iterate over the properties of an object. For example, the following code uses a for-in loop to iterate over the properties of an object and print their keys and values:

const obj = {
  name: "John",
  age: 30,
  job: "teacher"
};

for (let key in obj) {
  console.log(`${key}: ${obj[key]}`);
}
2. How can the `break` and `continue` statements be used with a `for` loop to control the flow of the loop?

The break statement can be used to immediately exit the loop and continue execution of the code after the loop, while the continue statement can be used to immediately skip to the next iteration of the loop, without executing the remaining code in the current iteration.

3. Are there any differences between a `for` loop and a `while` loop in JavaScript?

Yes. The for loop is typically used when you know in advance how many times the loop should run, whereas the while loop is used when you don't know how many times the loop should run and want to continue looping until a certain condition is met.

Additional Resources

The for...in Loop

The for...of Loop

The While Loop

The do...while Variation

Break and Continue in JavaScript

LoopInJavascript.com - an entire site about JavaScript loops

Loops and iteration on the MDN web docs

Advanced Loops video on YouTube