Tutorials

JavaScript ES6 Loops

Loops in JavaScript are essential for iterating over collections and objects, executing the same code block repeatedly until a condition is met. Take a look at this example:

let x = 0;

while (x < 5) {
  console.log(x);
  x++;
}

// logs 0, 1, 2, 3, 4

This while loop increments x until the condition x < 5 is no longer true.

Key Takeaways

  • JavaScript loops are categorized as either definite or indefinite based on their termination conditions.
  • Definite loops have a known number of iterations, including for, for...in, Array.forEach(), and for...of.
  • Indefinite loops rely on a condition and include while and do...while loops.
  • Control flow within loops can be managed using break and continue statements.
  • The for...of loop is preferred over for...in for arrays due to its performance and predictability.

Types of Loops

JavaScript loops are classified into two main groups: definite and indefinite loops. Let's delve into each category:

Definite Loops

Definite loops perform a set number of iterations. Here are the primary types:

For Loops

for (let i = 0; i < 5; i++) {
  console.log(i);
}

// logs 0, 1, 2, 3, 4

A for loop specifies the initial count, termination condition, and increment. This deliberate structure classifies it as a definite loop.

for...in Loops

let obj = { a: 1, b: 2 };

for (let key in obj) {
  console.log(key);
}

// logs 'a', 'b'

Although for...in is more suitable for object properties, it's not ideal for arrays.

Array.forEach()

The Array.forEach() method iterates through elements seamlessly:

let array = [1, 2, 3, 4];

array.forEach((x) => {
  console.log(x);
});

// logs 1, 2, 3, 4

for...of Loops

let array = [1, 2, 3, 4];

for (let x of array) {
  console.log(x);
}

// logs 1, 2, 3, 4

The for...of loop excels in iterating over iterable objects like arrays.

Indefinite Loops

Indefinite loops' termination depends on a condition, offering flexibility:

While Loops

let i = 0;

while (i < 5) {
  console.log(i);
  i++;
}

// logs 0, 1, 2, 3, 4

These loops run until their condition is false.

do...while Loops

let i = 0;

do {
  console.log(i);
  i++;
} while (i < 5);

// logs 0, 1, 2, 3, 4

The do...while loop assures execution at least once before condition checking.

Controlling Loops with break and continue

Using break to Exit

let array = [1, 2, 3];

for (let x of array) {
  if (x === 2) {
    break;
  }
  console.log(x);
}

// logs 1

The break statement allows for early loop termination.

Using continue to Skip

let array = [1, 2, 3];

for (let x of array) {
  if (x === 2) {
    continue;
  }
  console.log(x);
}

// logs 1, 3

Use continue to skip iterations conditionally.

for...of vs for...in

The for...of was introduced with ES6 to fix shortcomings in for...in, especially for arrays where order is crucial. Unlike for...in, which iterates over enumerable properties, for...of iterates over iterable objects, making it the preferred choice for arrays.

This upgrade mitigates issues such as additional enumerables and inconsistent order, maintaining compatibility with break and continue.

Conclusion

Loops are a fundamental aspect of JavaScript control flow, enabling functions to execute repetitively and efficiently. Now, you're prepared to explore more advanced control structures and decision-making paradigms in JavaScript.

FAQ

Why is for...of preferred over for...in for arrays?

The for...of loop is specifically designed for iterables like arrays, ensuring order and skipping unnecessary properties.

Can you use break and continue in Array.forEach()?

No, break and continue do not work with Array.forEach(). Consider a for...of loop if control flow keywords are necessary.

What's the main advantage of definite loops?

Definite loops provide predictable iteration counts, enhancing readability and debugging.

How does do...while differ from while?

The do...while loop guarantees at least one execution even if the condition fails initially, unlike while.

Mastering the tech interviewWhat everyone is doing wrong in tech interviews