DEV Community

Cover image for Understanding Loops in JavaScript
Ramkumar.barani
Ramkumar.barani

Posted on

1 1 1 1

Understanding Loops in JavaScript

Introduction

Loops are fundamental in JavaScript, allowing us to execute code repeatedly and iterate through data structures like arrays and objects. In this guide, we'll explore different types of loops, their use cases, and best practices to optimize your code.


Different Ways to Create a Loop in JavaScript

1. for Loop

The for loop is one of the most commonly used loops, giving you full control over iteration.

Syntax & Explanation:

for (let i = 0; i < 5; i++) {
  console.log(i); // Outputs 0 to 4
}
Enter fullscreen mode Exit fullscreen mode
  • let i = 0; → Initializes the loop counter.
  • i < 5; → The loop runs while this condition is true.
  • i++ → Increments the counter after each iteration.

When to Use:

  • When the number of iterations is known.
  • When precise control over each step is required.

2. while Loop

A while loop executes as long as its condition remains true.

Syntax & Explanation:

let i = 0;
while (i < 5) {
  console.log(i);
  i++;
}
Enter fullscreen mode Exit fullscreen mode
  • The condition i < 5 is checked before each iteration.
  • If true, the loop executes; otherwise, it stops.
  • i++ ensures the loop does not run indefinitely.

Be Careful: Infinite Loops

An infinite loop occurs if the condition never becomes false:

while (true) {
  console.log("This will run forever!");
  break; // Stops the loop
}
Enter fullscreen mode Exit fullscreen mode

When to Use:

  • When the number of iterations is unknown.
  • When looping depends on a condition instead of a fixed counter.

3. forEach (For Arrays)

forEach provides a concise way to iterate over arrays.

Syntax:

const numbers = [1, 2, 3, 4, 5];
numbers.forEach(num => console.log(num));
Enter fullscreen mode Exit fullscreen mode

When to Use:

  • When iterating through an array without modifying it.
  • When you do not need to exit the loop early (forEach does not support break).

Modern Ways to Loop

.map() – Transforming Data

.map() creates a new array by applying a function to each element.

const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
Enter fullscreen mode Exit fullscreen mode

Use .map() when:

  • You need a new array with modified values.
  • The main difference between forEach and map is that map returns a new array, whereas forEach does not.

.filter() – Filtering Data

.filter() returns a new array containing elements that meet a condition.

const numbers = [1, 3, 5, 7, 9, 2, 4, 6, 8];
const greaterThanFive = numbers.filter(num => num > 5);
console.log(greaterThanFive); // [7, 9, 6, 8]
Enter fullscreen mode Exit fullscreen mode

Use .filter() when:

  • You need to extract specific elements from an array.

Looping Through Objects

Objects are not directly iterable like arrays, but you can use for...in, Object.keys(), Object.values(), or Object.entries().

for...in

const user = { name: "John", age: 30, job: "Developer" };
for (let key in user) {
  console.log(`${key}: ${user[key]}`);
}
Enter fullscreen mode Exit fullscreen mode

Object.entries()

Object.entries(user).forEach(([key, value]) => {
  console.log(`${key}: ${value}`);
});
Enter fullscreen mode Exit fullscreen mode

Use these when:

  • Working with objects instead of arrays.
  • Efficiently iterating through properties.

Traditional vs. Modern Approaches

Example 1: Filtering & Transforming Data

Traditional Approach: Using a for Loop

const activeUsers = [];
for (let i = 0; i < users.length; i++) {
    if (users[i].status === 'active') {
        activeUsers.push({
            name: users[i].name,
            lastLogin: users[i].lastLogin
        });
    }
}
Enter fullscreen mode Exit fullscreen mode

Modern Approach: Using .filter() & .map()

const activeUsers = users
    .filter(user => user.status === 'active')
    .map(user => ({
        name: user.name,
        lastLogin: user.lastLogin
    }));
Enter fullscreen mode Exit fullscreen mode

Example 2: Doubling Even Numbers

Traditional Approach: Using a for Loop

const doubledEvens = [];
for (let i = 0; i < numbers.length; i++) {
    if (numbers[i] % 2 === 0) {
        doubledEvens.push(numbers[i] * 2);
    }
}
Enter fullscreen mode Exit fullscreen mode

Modern Approach: Using .filter() & .map()

const doubledEvens = numbers
    .filter(num => num % 2 === 0)
    .map(num => num * 2);
Enter fullscreen mode Exit fullscreen mode

Best & Bad Practices

✅ Best Practices

  • Use .map() and .filter() for cleaner transformations.
  • Use for...of for better readability when looping over arrays.
  • Use Object.entries() for efficient object iteration.

❌ Bad Practices

  • Avoid modifying arrays directly inside loops.
  • Avoid for...in for arrays (it iterates over properties, not values).
  • Be cautious with infinite loops (while (true) {} without break).

Performance Considerations

  • for loops are generally the fastest since they avoid function calls.
  • map, filter, and forEach are more readable but slightly slower.
  • For large datasets, use for loops when performance is critical.

Conclusion

Loops are essential in JavaScript, and choosing the right one depends on the use case. Modern array methods like .map() and .filter() help write cleaner, more maintainable code. Understanding the trade-offs between readability and performance will make you a better JavaScript developer. Start experimenting with these techniques today! 🚀

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

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

Okay