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.

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)

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

👋 Kindness is contagious

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

Okay