DEV Community

Cover image for Getting Loopy with JavaScript
Dallas Reedy
Dallas Reedy

Posted on • Originally published at blog.dallasreedy.com

Getting Loopy with JavaScript

Here are five ways you can loop 5 times in JavaScript and do something with a different value each time through the loop:

/* totally manual with a while loop */
let i = 0;
while (i < 5) {
  console.log(`Hello, ${i}!`);
  i++;
};

/* classic for loop */
for (let j = 0; j < 5; j++) {
  console.log(`Hello there, ${j}!`);
}

/* new-age for...of loop */
for (let k of [0, 1, 2, 3, 4]) {
  console.log(`Hello once more, ${k}!`);
}

/* using forEach with manually filled array */
[0, 1, 2, 3, 4].forEach(
  l => console.log(`Hello again, ${l}!`)
);

/* auto-fill an array of length 5 and use indices */
Array(5).fill().forEach(
  (_,m) => console.log(`Hello one last time, ${m}!`)
);
Enter fullscreen mode Exit fullscreen mode

What other ways can we loop a specific number of times in JavaScript?

Warm regards,
Dallas

Top comments (0)