Looping Through Arrays in JavaScript

The main reason we use arrays is to store a lot of values in a single place. So, it would make sense that we had a way to iterate or loop through these values in a simple way. So, JavaScript has a way to loop through an array using built-in methods like: map(), forEach(), filter(), etc.

Rather than typing array[0], array[1], array[2], etc every time to access all of it’s items, we will use loops for it.

The most popular loops used in arrays in JavaScript are as follows:


JavaScript for loop in Arrays 🔄

The most basic way of looping through an array is by using the for loop. It’s syntax is explained in our 👉 JavaScript For Loop lesson

Example

let animals = ["Lion", "Deer", "Bear", "Monkey", "Zebra"];

console.log("The available animals in our zoo are:");

for (let i = 0; i < animals.length; i++) {
  console.log(animals[i]);
}

Output

The available animals in our zoo are:
Lion
Deer
Bear
Monkey
Zebra

Besides the for loop, JavaScript provides built-in array methods for iterating over an array quickly and efficiently. They are as follows.


JavaScript forEach method 🧮

The forEach() method is one of the most widely used built-in array methods in JavaScript to loop over an array.

The forEach() method takes a function as an argument and calls it.

Note: Whenever we use a function as an argument in another function, that function which is used as an argument is called a Callback Function.

Syntax

Array.forEach(function(currentValue, index, array))

How it works?

  • The forEach() method takes a function an argument.
  • The function takes three arguments: currentValue(required), index(optional) and array(optional)

Parameters

  • currentValue : It is required. It contains the value of the current element that we are iterating at the moment.
  • index : It is optional. It contains the index of the current element.
  • array : It is optional. It contains the entire array.

Example

let animals = ["Lion", "Deer", "Bear", "Monkey", "Zebra"];

console.log("The available animals in our zoo are:");

animals.forEach(printAnimals);

// We are defining the iterating function here. We can also define it above the forEach method
function printAnimals(currentValue, index) {
  console.log(`${currentValue} at index ${index}`);
}

Output

The available animals in our zoo are:
Lion at index 0
Deer at index 1
Bear at index 2
Monkey at index 3
Zebra at index 4

JavaScript map() method 🗺

The map() method in JavaScript iterates or loop over the given array and returns a new array by calling a function on each element of the array.

Note: The map() method does not change the original array.

Syntax

Array.map(function(currentValue, index, array))

How it works?

  • The map() method takes a function an argument.
  • The function takes three arguments: currentValue(required), index(optional) and array(optional)

Parameters

  • currentValue : It is required. It contains the value of the current element that we are iterating at the moment.
  • index : It is optional. It contains the index of the current element.
  • array : It is optional. It contains the entire array.

Returns

  • A new array.

Example

let animals = ["Lion", "Deer", "Bear", "Monkey", "Zebra"];

function toPlural(currentValue) {
    return currentValue + "s";
}

const animalsInPlural = animals.map(toPlural);

console.log("The available animals in our zoo are:");
console.log(animalsInPlural);

Output

The available animals in our zoo are:
[ 'Lions', 'Deers', 'Bears', 'Monkeys', 'Zebras' ]

JavaScript filter() method ⏳

The filter() method in JavaScript iterates over the given array and returns a new array containing only the elements that passed the test condition provided by the given function.

In other words, it filters the given array.

Note: The filter() method does not change the original array.

Syntax

Array.filter(function(currentValue, index, array))

How it works?

  • The filter() method takes a function an argument.
  • The function takes three arguments: currentValue(required), index(optional) and array(optional)

Parameters

  • currentValue : It is required. It contains the value of the current element that we are iterating at the moment.
  • index : It is optional. It contains the index of the current element.
  • array : It is optional. It contains the entire array.

Returns

  • A new filtered array.

Example

let numbers = [2, 3, 4, 5, 6, 7, 8];

function filterEvenNumbers(currentValue) {
  // The ampersand "%" operator generates remainder obtained when dividing "currentValue" by "2".
  // And for even numbers, the remainder is 0. So the "===" operator returns "true" when the number is even.
  return currentValue % 2 === 0;
}

const evenNumbers = numbers.filter(filterEvenNumbers);

console.log("List of even numbers:");
console.log(evenNumbers);

Output

List of even numbers:
[ 2, 4, 6, 8 ]

JavaScript find() method 🔎

The find() method in JavaScript iterates over the given array and returns the first element that passes the test condition provided by the given function.

In other words, it finds an element from the list of elements in the array.

Note:

  • The find() method does not change the original array.
  • The find() method returns undefined if there are no elements that pass the given test provided by the function.

Syntax

Array.find(function(currentValue, index, array))

How it works?

  • The find() method takes a function an argument.
  • The function takes three arguments: currentValue(required), index(optional) and array(optional)

Parameters

  • currentValue : It is required. It contains the value of the current element that we are iterating at the moment.
  • index : It is optional. It contains the index of the current element.
  • array : It is optional. It contains the entire array.

Returns

  • A value if passes the test condition, otherwise returns undefined.

Example

let numbers = [2, 3, 4, 5, 6, 7, 8];

function findGreaterThan5(currentValue) {
  // The elements: 2, 3, 4 and 5 will fail this test.
  // The first element that passes this test will be "6". So, the "find" method will return 6.
  return currentValue > 5;
}

const numberGreaterThan5 = numbers.find(findGreaterThan5);

console.log("Number greater than 5:");
console.log(numberGreaterThan5);

Output

Number greater than 5:
6

JavaScript reduce() method 🤏

The reduce() method in JavaScript executes the given function on each array element and returns a single value.

In other words, it reduces the list of elements in the array to a single value.

Note: The reduce() method does not change the original array.

Syntax

Array.reduce(function(total, currentValue, currentIndex, array), initialValue)

How it works?

  • The reduce() method takes two arguments: a function which is called a reducer function and an initialValue.
  • The reducer function then takes four arguments: total(required), currentValue(required), index(optional) and array(optional)

Parameters

  • For the reducer function:
    • total : It is required. It is the initial value or the previously returned value by the function.
    • currentValue : It is required. It contains the value of the current element that we are iterating at the moment.
    • index : It is optional. It contains the index of the current element.
    • array : It is optional. It contains the entire array.
  • initialValue : It is optional. It is the value which is passed at the very beginning of the loop, telling the reduce() function to start from this given value.

Returns

  • A single value obtained by reducing the array.

Example

let numbers = [2, 3, 4];

function sum(total, currentValue) {
  console.log(`Total is: ${total}. Current value is: ${currentValue}. Next total is: ${total}+${currentValue}`);
  return total + currentValue;
}

const sumOfTheNumbers = numbers.reduce(sum);

console.log("The sum is:");
console.log(sumOfTheNumbers);

Output

Total is: 2. Current value is: 3. Next total is: 2+3
Total is: 5. Current value is: 4. Next total is: 5+4
The sum is:
9

JavaScript includes() method 😏

The includes() method in JavaScript returns true when the array contains the given value and false when it doesn’t.

Syntax

Array.includes(value, startPosition)

Parameters

  • value : It is required. It is the value that we are searching for, in the array.
  • startPosition : It is optional. It is the index from where the includes() method should start the search from. By default, it is 0.

Example

const friends = ["Harry", "John", "Alice"];

// Returns "true" as "Alice" belongs to the array "friends"
console.log(friends.includes("Alice"));
// Returns "false" as "Chris" does not belong to the array "friends".
console.log(friends.includes("Chris"));
// Returns "false" as "Harry" does not belong to the array when we start from index position "1".
console.log(friends.includes("Harry", 1));

Output

true
false
false

JavaScript every() method 💯

The every() method in JavaScript returns true only when all the elements in the array passes the test condition provided by the given function.

If even one of the elements in the given array does not pass the test condition, the every() method returns false.

Note: The every() method does not change the original array.

Syntax

Array.every(function(currentValue, index, array))

How it works?

  • The every() method takes a function an argument.
  • The function takes three arguments: currentValue(required), index(optional) and array(optional)

Parameters

  • currentValue : It is required. It contains the value of the current element that we are iterating at the moment.
  • index : It is optional. It contains the index of the current element.
  • array : It is optional. It contains the entire array.

Returns

  • A single boolean value: true if all the elements pass the test condition, otherwise false.

Example

const numbers = [2, 3, 4, 6, 8, 10];
const moreNumbers = [12, 14, 16, 18, 20];

function isEven(value) {
  return value % 2 === 0;
}

// Here, the test condition in the "isEven" function is "true" for all the elements except "3", so the "every()" method returns false
console.log(numbers.every(isEven));
// Here, the test condition in the "isEven" function is "true" for all the elements, so the "every()" method returns true
console.log(moreNumbers.every(isEven));

Output

false
true

JavaScript some() method 🙄

The some() method is the exact opposite of the every() method.

The some() method in JavaScript returns true even when only one of the elements in the given array passes the test condition provided by the given function.

If none of the elements in the given array pass the test condition provided, then the some() method returns false.

Note: The some() method does not change the original array.

Syntax

Array.some(function(currentValue, index, array))

How it works?

  • The some() method takes a function an argument.
  • The function takes three arguments: currentValue(required), index(optional) and array(optional)

Parameters

  • currentValue : It is required. It contains the value of the current element that we are iterating at the moment.
  • index : It is optional. It contains the index of the current element.
  • array : It is optional. It contains the entire array.

Returns

  • A single boolean value: true even if only one of the elements pass the test condition otherwise false.

Example

const numbers = [2, 3, 4, 5, 7];
const moreNumbers = [3, 5, 7, 9, 11];

function isEven(value) {
  return value % 2 === 0;
}

// Here, the test condition in the "isEven" function is "true" for some of the elements i.e. "2" and "4", so the "some()" method returns true
console.log(numbers.some(isEven));
// Here, the test condition in the "isEven" function is "false" for all of the elements, so the "some()" method returns false
console.log(moreNumbers.some(isEven));

Output

true
false

In this way, we can iterate over arrays easily and efficiently by using the built-in array methods provided by JavaScript 🤯.