The classic for loop is a widely used feature of javascript programs. It can be used for running any piece of code multiple times, and it used to be what was used for implementing operations on arrays.
A typical for loop would look something like this:
var arr ['a', 'b', 'c', 'd', 'e'];
for (var i 0; i < arr.length; i++) {
console.log(arr[i]);
}
It gets the job done, but nowadays there are alternatives that may be more suitable for operating on arrays, which I’ll refer to as array functions.
These functions, like map, reduce and filter are part of the Array prototype. Some of them have been around for some time and have great browser support (down to IE9).
Some newer array functions like find became standard as part of ES2015 so have less support, but can be very handy.
Depending on your project requirement and setup, you may still want to use them.
So, why would you want to use array functions instead of the good old for loop?
There are several reasons:
- Usually it results in shorter, more readable code
- You don’t have to define some temporary helper variables (like I above)
- Array elements are directly available for processing and you don’t have to access them using the index
- The array functions are more expressive and convey better what the code does compare with the generic keyword
- The new functions are not prone to ‘off by one bugs
- If you are into functional programming, using loops is discouraged (to put it mildly)
Now I wan’t deny that the classic for loop does have some benefits:
- It is very flexible
- It’s supported everywhere javascript runs
- It has better performance than the specialized array functions
In most cases, however, the benefits of array functions win over those of the for loop and should be used.
If you want to start using array functions, read on to see a couple of examples of common array operations that implement the same logic using both for and the newer functions.
The example array
All the following examples will assume that this array is defined and available in the scope:
var people [{
id: 1,
name: 'Alice',
age: 16
},
{
id: 2,
name: 'Bob',
age: 19
},
{
id: 3,
name: 'Carol',
age: 15
},
{
id: 4,
name: 'David',
age: 21
}];
Sum an array
Let’s find the sum of the ages of the people in our array. This can be useful for calculating the average age for example.
Using for:
var sum 0;for (var i 0; i < people.length; i++) { sum += people[i].age; }
Using Array.reduce:
const sum people.reduce(function(acc, person){
return acc + person.age;
}, 0)
If we combine reduce with the ES6 arrow functions, we can get even shorter, more focused code.
Using Array.reduce + arrow functions:
const sum people.reduce((acc, person) > (acc + person.age), 0);
Interlude: a note about arrow functions
Arrow functions are part of the ES2015 standard and are really cool, so I’ll be using them in the rest of the examples – they work very well with array functions.
If you are not familiar with arrow functions, know that they are natively supported in all modern browsers but not in IE and you can read a nice intro on using them in this article.
If you are still uncomfortable using arrow functions, it’s usually trivial to replace them in the examples with regular javascript functions.
Filter an array
Let’s say we want an array with just the records for adults.
Using for:
var adults [];for (var i 0; i < people.length; i++) { if (people[i].age > 16) { adults.push(people[i]); } }
Using Array.filter:
const adults people.filter(person > person.age > 16);
Find the element with max property
Say we want to find the record of the oldest person in our array.
Using for:
var oldest {age: 0};for (var i 0; i < people.length; i++) { if (people[i].age > oldest.age) { oldest people[i]; } }
Using Array.reduce:
const oldest people.reduce((acc, person) >
person.age > acc.age ? person : acc
);
Extract a property from an array of objects
Say we need an array with just the names, let’s see how to create it.
Using for:
var names [];for (var i 0; i < people.length; i++) { names.push(people[i].name); }
Using Array.map:
const names people.map(val > val.name);
Index an array of objects
Sometimes it’s beneficial to index an array of objects by one of the properties in the objects. For example, you might want to index the array by an ID property so you could more efficiently look up objects in the array.
Continuing with the example array, Let’s see how to do that:
Using for:
var iPeople {};for (var i 0; i < people.length; i++) { iPeople[people[i].id] people[i]; }
Using Array.reduce:
const iPeople people.reduce((acc, person) > {
acc[person.id] person;
return acc;
}, {});
Find an element in array
Say we want to find the first record for a given name.
Using for:
var details null;for (var i 0; i < people.length; i++) { if (people[i].name == 'Bob'){ details people[i]; break; } }
Using Array.find:
const details people.find(val > val.name == 'Bob');
Note that find is not supported in IE but is natively supported in all modern browsers and there’s a polyfill.
Summary
As you can see from the examples above, the new array functions are very useful, easy to work with and result in shorter, more readable code.
There are more array functions that were not demonstrated here, but if you are interested, they are very well documented on MDN.
Most of the array functions in this article are natively supported in all modern browsers all the way down to IE9. One exception is Array.find which is only supported by Edge 12