Monday, October 27, 2014

Iterator methods of Array in JavaScript

In this post I will summarize iterator methods of Array in JavaScript. Programmers often forget that these useful functions are part of the language and mindlessly connect third-party libraries.

Iterator methods apply a function to each element of an array, either returning a value, a set of values, or a new array after applying the function to each element of an array.

Non Array generating iterator methods

The forEach() method takes a function as an argument and applies the called function to each element of an array.

function square(num) {
print(num, num * num);
var nums = [1,2,3,4,5,6,7,8,9,10];

The every() method applies a Boolean function to an array and returns true if the function can return true for every element in the array.

function isEven(num) {
return num % 2 == 0;
var nums = [2,4,6,8,10];
var even = nums.every(isEven);
if (even) {
print("all numbers are even");
else {
print("not all numbers are even");

The some() method will take a Boolean function and return true if at least one of the elements in the array satisfies the condition of the Boolean function.

function isEven(num) {
return num % 2 == 0;
var nums = [1,2,3,4,5];
var someEven = nums.some(isEven);
if (someEven) {
print("some numbers are even");
else {
print("no numbers are even");

The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) has to reduce it to a single value.

function add(previousValue, currentValue) {
return previousValue + currentValue;
var nums = [1,2,3,4,5,6,7,8,9,10];
var sum = nums.reduce(add);
print(sum); // displays 55

The reduceRight() method which works similarly to reduce(), only working from the righthand side of the array to the left, instead of from left to right.

function concat(accumulatedString, item) {
return accumulatedString + item;
var words = ["the ", "quick ","brown ", "fox "];
var sentence = words.reduceRight(concat);
print(sentence); // displays "fox brown quick the"

Iterator methods that return a new Array

The map() method works like the forEach() method, applying a function to each element of an array. The difference between the two methods is that map() returns a new array with the results of the function application.

var numbers = [1, 4, 9];
var doubles = {
return num * 2;
// doubles is now [2, 8, 18]. numbers is still [1, 4, 9]

The filter() method works similarly to every(), but instead of returning true if all
the elements of an array satisfy a Boolean function, the method returns a new array
consisting of those elements that satisfy the Boolean function.

function isBigEnough(element) {
 return element >= 10;
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]