DEV Community

Mike Turck
Mike Turck

Posted on

JavaScript For Loop Examples

Standard For Loop

for (let i = 0; i < 5; i++) {
  console.log(`Iteration ${i + 1}`);
}
Enter fullscreen mode Exit fullscreen mode

For...of Loop (Iterating over Arrays)

const fruits = ['apple', 'banana', 'orange'];
for (const fruit of fruits) {
  console.log(fruit);

Enter fullscreen mode Exit fullscreen mode

For...in Loop (Iterating over Object Properties)

const person = {
  name: 'John',
  age: 30,
  job: 'Developer'
};

for (const key in person) {
  console.log(`${key}: ${person[key]}`);
}
Enter fullscreen mode Exit fullscreen mode

forEach Loop (Array Method)

const numbers = [1, 2, 3, 4, 5];
numbers.forEach((number, index) => {
  console.log(`Index ${index}: ${number}`);
});
Enter fullscreen mode Exit fullscreen mode

While Loop (Not technically a for loop, but worth mentioning)

let count = 0;
while (count < 3) {
  console.log(`Count: ${count}`);
  count++;
}
Enter fullscreen mode Exit fullscreen mode

These examples demonstrate various ways to iterate in JavaScript, each suited for different scenarios and data structures.

Top comments (0)