DEV Community

Cover image for Getting Loopy with JavaScript
Dallas Reedy
Dallas Reedy

Posted on • Originally published at blog.dallasreedy.com

2

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

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay