Have you ever had an array of items in Javascript and wondered “I’d sure like to iterate through these items in a specific way?” Well, here’s a handful of methods you can use!

Classic for Loop

The ugly, but quick and standard has been the for loop. This will let you go through an array, perform any number of actions for each item in the array, with the option to exit out of the loop whenever you’re done!

let fruits = ['apple','pear','orange','pineapple','plum','kiwi'];

for (let x = 0; x < fruits.length; x++) {
    if (fruits[x] !== 'pineapple') {
        console.log('This is not a pineapple');
    } else {
        console.log('This IS a pineapple');
        break;
    }
}

In this example, you’ll notice that “This is not a pineapple” will get printed 3 times in the console, then we’ll finally reach our beloved fruit and hit the else statement, and the break will let us escape the loop, as we have no desire to continue looking through our fruit array.

The forEach method

There is a cleaner way to iterate through arrays and that’s by using the newer forEach method. It works almost the same as before, with much less of a mess:

let fruits = ['apple','pear','orange','pineapple','plum','kiwi'];

fruits.forEach( (fruit) => {
    if (fruit !== 'pineapple') {
        console.log('This is not a pineapple');
    } else {
        console.log('This IS a pineapple');
    }
});

Much nicer! However, if you run this you will notice that unlike before, we’ll get a few more “This is not a pineapple” lines printed in our console. This is the major caveat with this method, in that it will iterate through every item in the array, and there’s nothing you can do about that. If that isn’t an issue however, it certainly is a more readable syntax for a full iteration. There are some other variations like for...in and for...of that work in similar, but distinct ways which we won’t discuss here.

Fancy filter

If a thorough iteration is in the cards, and you have a specific goal like creating a subset out of the initial array, then there is a handy method you can choose instead of the standard forEach. Let’s compare them:

let fruits = ['apple','pear','orange','pineapple','plum','kiwi'];
let pFruits = [];

fruits.forEach( (fruit) => {
    if ( fruit.startsWith('p') ) pFruits.push(fruit);
});

Using a forEach to get a new array of just fruits beginning with “p” will require us to define the empty array beforehand (forEach just returns undefined) and then separately push the matching values into it. It doesn’t look too bad, but we can make it even easier!

let fruits = ['apple','pear','orange','pineapple','plum','kiwi'];
let pFruits =  fruits.filter( (fruit) => {
    return fruit.startsWith('p');
});

Using the filter method will return the new array for you, so we can go ahead and assign it straight to the variable we want. Our check is also simplified as any item that meets the return condition will be passed through into the new array. Lastly, we have something that falls in between the straight-laced forEach with the processing simplifications of the filter method…

Let’s map Things Up

Now remember, the filter method effectively will create a subset of the initial array, based on some filtering condition. If we wanted to alter the array as a whole, then we could just use map instead. Once again, the forEach version would look like:

let fruits = ['apple','pear','orange','pineapple','plum','kiwi'];
let piesAndPineapple = [];

fruits.forEach( (fruit) => {
    if ( fruit === 'pineapple' ) {
        piesAndPineapple.push(fruit);
    } else {
        piesAndPineapple.push(`${fruit} pie`);
    }
});

Since no one wants a pineapple pie, we decided to turn all our other fruits into one while maintaining our favorite food’s identity. If we map this, it would simplify to:

let fruits = ['apple','pear','orange','pineapple','plum','kiwi'];
let piesAndPineapple = fruits.map( (fruit) => {
    return ( fruit === 'pineapple' ) ? fruit : `${fruit} pie`;
});

With map simply needing a returned value, we can go ahead and inline our conditional to our 2 possibilities. Once again, the new array is returned by this method letting us assign it straight to our variable, and we’re all set! There’s many more things an array can do, you can see a full list over here, but this covers some basic ones that you’ll probably want to use at some point or another.