Iteration and Control Flow

Iteration is the repeated execution of a set of statements. JavaScript offers multiple ways to loop through data, each suited for different data structures and performance requirements.


1. Traditional Loops: for and while

These provide the most granular control over the iteration process.


2. Iterating over Objects and Arrays

Modern JavaScript provides specialized loops for different data types:

I. for...of (The Modern Standard)

Used for iterating over Iterables (Arrays, Strings, Sets, Maps). It provides the actual Value of each element.

const fruits = ["apple", "banana", "cherry"];
for (const fruit of fruits) {
    console.log(fruit);
}

II. for...in (The Object Explorer)

Used for iterating over the Enumerable Properties (Keys) of an object.


3. Functional Iteration: forEach

The forEach method is a built-in array method that executes a provided function once for each array element.

fruits.forEach((fruit, index) => {
    console.log(`${index}: ${fruit}`);
});

4. Performance and Efficiency


Interview Pro-Tips: The for...in trap

If an interviewer asks why you shouldn't use for...in for arrays:

  1. It iterates over the Keys (0, 1, 2 as strings), not the values.
  2. It is slower because it traverses the entire Prototype Chain.
  3. The iteration order is not guaranteed to be consistent across different engines. Always use for...of or forEach for arrays.

Technical Summary

  1. Iterable: An object that implements the [Symbol.iterator] method.
  2. Control: Use break to exit early and continue to skip the rest of the current iteration.
  3. Paradigm: Functional methods (map, filter, reduce) are often preferred over manual loops for better readability and declustered state.