Array.Prototype.forEach() & Array.Prototype.some() Methods

Understanding Array.Prototype.forEach() & Array.Prototype.some() Methods


The ES6 version of JavaScript unwraps the array iteration methods that help JavaScript developers to write clean and readable code.

Some of these iteration methods are immutable, which means they do not change the original array.

This article will be focused on making these two array iteration methods easy for you to understand by creating a fun, interesting and easy learning experience to its readers.

Let’s have fun as we get started.

Recently, I have found much interest in watching wrestling matches and I feel WWE is cool. Let’s have some fun using the WWE superstars to foster interest while we learn the forEach method. Common guys, let’s check out our WWE superstars…….

// WWE superstars array
let wweSuperstars = [
   {
      'id': 001,
      'first_name': 'Brock',
      'last_name': 'Lesnar',
      'ring_name': 'Brock Lesnar',
      'gender': 'M',
      'Nationality': 'Portugal',
      'Height': '6.3ft',
      'weight': '286 lbs',
      'age': 32,
      'achivement': [WWE, smackdown,]     
   },
   {
      'id': 002,
      'first_name': 'Franklin',
      'last_name': 'Lashley',
      'ring_name': 'Bobby Lashley',
      'gender': 'M',
      'Nationality': 'Portugal',
      'Height': '6.3ft',
      'weight': '273 lbs',
      'age': 32,
      'achivement': [WWE, smackdown,]     
   },
{
      'id': 003,
      'first_name': 'Randal',
      'last_name': 'Orton',
      'ring_name': 'Randy Orton',
      'gender': 'M',
      'Nationality': 'Germany',
      'Height': '6.5ft',
      'weight': '245 lbs',
      'age': 32,
      'achivement': [WWE, smackdown,]     
   },
{
      'id': 004,
      'first_name': 'Oscar',
      'last_name': 'Gutierrez,
      'ring_name': 'Rey Misterio',
      'gender': 'M',
      'Nationality': 'France',
      'Height': '5.6ft',
      'weight': '347 lbs',
      'age': 32,
      'achivement': [WWE, smackdown,]     
   },
{
      'id': 005,
      'first_name': 'Colby',
      'last_name': 'Lopez',
      'ring_name': 'Seth Rollins',
      'gender': 'M',
      'Nationality': 'Portugal',
      'Height': '71ft',
      'weight': '347 lbs',
      'age': 32,
      'achivement': ["Raw tag team champion"]     
   },

];

Brace-up, let’s go have some fun learning these iteration methods.

Array.prototype.forEach() iteration method

The ES6 Array.prototype.forEach() method triggers a call to the provided callback function once for each element in an array in ascending order. For array items that have been deleted or are uninitialized, the Array.prototype.forEach() method will not be executed.

Syntax
const eachItem = myArray.forEach(callbackFunction);

Callback function

Syntax
callback(element, index, array)

This is the function that houses the conditions to be executed over each element of the array. 

The callback function receives 3 parameters which include:

  • array: the array that is currently being processed. It is optional.
  • index: the index of the current item in the array. It is optional.
  • element: this is the element currently being executed. It is usually required.

The Array.prototype.forEach() method in action

Let’s implement a feature to log the nationalities of all our WWE superstars to the console.

// Add the variable wweSuperstars from the first code snippet
/* Here */
const getNationality = () => wweSuperstars.forEach((superstar) => {
   console.log( `Nationality: ${superstar.Nationality}` );
});
getNationality();

Results

 Nationality: Portugal
 Nationality: Portugal
 Nationality: Germany
 Nationality: France
 Nationality: Portugal

How the Array.prototype.forEach() method handles sparse arrays

Sparse arrays are arrays containing uninitialized values.

const sparseArray = ["John Cena","Alberto del Rio", ,"Kane", "Undertaker", ,]
let numOfCallbackInvocation = 0

sparseArray.forEach((element) => {
  console.log(element)
  numCallbackRuns++
})

console.log("Num of Callback Invocation: ", numOfCallbackInvocation)

// John Cena
// Alberto del Rio
// Kane
// Undertaker
// Num of Callback Invocation: 4

Did you notice that the callback function was not invoked for the uninitialized values of the array which is located after the array element Alberto del Rio and also after the array element Undertaker.

Downside of the Array.prototype.forEach() method

During iteration, If the array is modified other elements might be skipped. This is a common downside in the forEach array method. 

Let’s consider the code snippet below

let words = ['Raw', 'Smackdown', 'Impact', 'Wrestle Mania']
words.forEach(function(word) {
  console.log(word)
  if (word === 'Smackdown') {
    words.shift()
  }
})
// Raw
// Smack down
// Wrestle Mania

Why is the third element in the array not logged to the console? Let’s see the reason for this abnormality.

The following example logs “Raw”, “Smackdown” and “Wrestle Mania”.

When the entry containing the value “Smackdown” is reached, the first entry of the whole array is removed from the array, resulting in all remaining entries moving up one position.

Because element “Impact” now has the index associated with its preceding element (Smackdown which had the index of 1) which has already been executed.

Index

The index parameter of the callback function is applicable in getting an element in an array at a specific index.

Let’s illustrate with the code snippet below:

// find array item with index of 2

const playerAtIndex = myFavouritePlayers.find((player, index)=> index === 2)

// display array item found

console.log(playerAtIndex)
// milk

Array.prototype.some()

The Array.prototype.some() method tests whether at least one element in the array passes the test implemented by the provided function.

t returns a Boolean value. Its callback function is invoked only for indexes of the array with assigned values. It is not invoked for indexes that have been deleted or which have never been assigned values. The some() method is immutable hence it does not change the original array.

Syntax

myArray.some(callback, thisArg)
Callback function

Syntax

callback(element, index, array)

This is the function that houses the conditions to be executed over each element of the array. 

The callback function receives 3 parameters which include:

  • array: the array that is currently being processed. It is optional.
  • index: the index of the current item in the array. It is optional.
  • element: this is the element currently being executed. It is usually required.

Some use cases of the Array.prototype.some() method

1. Checking whether a value exists in an array

// Add the variable wweSuperstars from the first code snippet
/* Here */

function checkNationality(superStars, nationality) {
  return superStars.some(superStar => superStar.Nationality === nationality);
}

checkNationality(wweSuperstars, 'Portugal'); // true  
checkNationality(wweSuperstars, 'Nigeria'); // false

In the above code snippet, we used the Array.prototype.some method to check the nationality of our WWE superstars.

The first checkNationality function call checks if there is any WWE superstar with the value of its Nationality property as Portugal while The second checkNationality function call checks if there is any WWE superstar with the value of its Nationality property as Nigeria and in this case, a Boolean value of false is returned because the value Nigeria does not exist.  

2. Testing the value of array elements

// Add the variable wweSuperstars from the first code snippet
/* Here */

function isOlderThan40(wweSuperstar, index, array) {
  return wweSuperstar.age > 40;
}

function isYoungerThan50(wweSuperstar, index, array) {
  return wweSuperstar.age < 50;
}

wweSuperstars.some(isOlderThan40);  // false
wweSuperstars.some(isYoungerThan50); // true

Conclusion

The ES6 Array.prototype.forEach( method triggers a call to the provided callback function once for each element in an array in ascending order while the Array.prototype.some() method tests whether at least one element in the array passes the test implemented by the provided function.

It returns a Boolean value based on the outcome of the test. For array items that have been deleted or are uninitialized, the callback function for both methods will not be executed.


Share on social media

//