...

/

The Convenience of Enhanced for

The Convenience of Enhanced for

Get introduced to the enhanced for loop and how it replaces the traditional for loop.

Iterating over a collection of values is commonplace, yet the code to loop through and process elements has been cumbersome in the past.

Using the traditional for loop to iterate

The for loop is arguably one of the most widely used constructs in C-like languages.

Example

Here’s an example that uses the for loop to iterate over a list of names and print each element.

Press + to interact
'use strict';
//START:CODE
const names = ['Sara', 'Jake', 'Pete', 'Mark', 'Jill'];
for(let i = 0; i < names.length; i++) {
console.log(names[i]);
}
//END:CODE

This loop is very familiar, but it is far from being simple—it has way too many moving parts. First, we had to initialize the variable i. Then, we set its upper bound and paused to grimace, wonder if it should be < or <=, and finally decide between pre-increment and post-increment. The assault continues within the loop because we have to access the element in the collection based on the value of the index variable i.

Advantages of the traditional for loop

No doubt, the for loop is quite ...