DEV Community

Tolumide Shopein
Tolumide Shopein

Posted on

Javascript DataTypes: Array Methods with Practical Examples (forEach and map)

In this short tutorial, I would be introducing (for lack of a better word) you to the Javascript forEach and map methods of arrays.

forEach Method

Code 1.1.
array.forEach(function(item, index, arr), thisArg)

The forEach method accepts two arguments, a callback function and a
second argument that specifies the value of this for each item in the array. If the thisArg value isn’t specified, then its value would be undefined.

However, you would commonly find the forEach method of an array called only with the first argument (the callback function,thus assigning an undefined value to the second argument by default) as in 1.2 and 1.3 below and that is what I would explain:

Code 1.2.
array.forEach((item, index, arr) => {})

Or as:

Code 1.3
array.forEach((item) => {})

The forEach method allows you loop through each item of an array while performing a function on such item. I think it’s okay to call the forEach method an iterative array method and important to note that this method does not return any result.

Basically, the forEach method accepts one argument (the callback function, used here as an arrow function) which accepts three arguments.

  1. The first argument is the current item in the array (during the iteration) (required),
  2. The second argument refers to the position (index) of the current item in the array (optional),
  3. The third argument is the array itself (optional).

Basic Example:

const arr = 1, 2, 3, 4, 5, 6]
    arr.forEach((item, index, arr) => {
    console.log(`${item} on index ${index} in ${arr}`)
});

NB: Most of the time you would only need and commonly see the array method implemented with the first argument (item) of the callback function.
NB: Copy out all examples and try them out on your browser's console

Practical Example:

Assume we are expecting data from an API(Application Programming Interface) which contains the username, data and other details but not in the format we need to render it to our user. Perhaps we need to format some elements in such data first?, show only some of the data? or perhaps add extra information to such array before it is rendered to the user without editing the original array because you still need it for something elsewhere. Well, this is a beautiful situation where you might need the forEach method.

const apiResponse = [{
  user: {firstname: 'tolumide', lastname: 'mic'},
  birthday: 'Sun Oct 15 2017 01:00:00 GMT+0100 (West Africa Standard Time)',
  phone: 070237461283
  },
  {
  user: {firstname: 'adeotun', lastname: 'ade'},
  birthday: 'Fri Mar 15 2013 01:00:00 GMT+0100 (West Africa Standard Time)',
  phone: 08111111111
}]
const modifiedResponse = [];
const assignValue = apiResponse.forEach(item => {
  const newObj = {
    fullname: `${item.user.firstname} ${item.user.lastname}`,
  phone: item.phone
 }
  modifiedResponse.push(newObj)
})

If we print the value of assignValue we would get undefined, however if we console the value of modifiedResponse we should get:

[{fullname: 'tolumide mic', birthday: '10/15/2017', phone: 070237461283}, {...}]

What did we do here?
We can’t display an object containing first name and last name where we ought to display them together as full name or display display an unformatted date to the user. So what do we do? We loop through each content, making a new item containing the formatted information as we need to display it and then push it into a new array (modifiedResponse ) which we would use for display to the user.

forEach method does not return a value:

const names = ['tolumide', 'ibukunoluwa', 'adebowale', 'oluwaseyi']
const capNames = names.forEach(names => {
  return name.toUpperCase();
})

capNames above would return undefined becase the forEachmethod does not return a result.

===> undefined

Map Method

Code 2.1

array.map(function(item, index, arr), thisArg)

The map method accepts two arguments, a callback function and a second parameter that would be used as to assign the value of this for each invocation of the callback function(first argument). If the second parameter (i.e the value of this) is not provided, then its value would be undefined.

Common representation:

Code 2.2

array.map((item, index, arr) => {})

Code 2.3

array.map((item) => {})

The map method like the forEach method loops through each item in the array. However, unlike the forEach method, the map method returns a new array containing the results of the function on each item of the original array.

It does this by calling the callback function presented to it on each item in the array, and returning a result on completion. Like the forEach method of arrays, the callback function in the map method accepts three arguments (item, index, and array).

  1. Item: The current item in the array during iteration (required)
  2. Index: The position of the current element during iteration in the array (optional)
  3. Array: The array been transformed (optional)

Practical Example:
Using the map method to create a new array where we capitalise the first letter of each item in the array.

Loop through all elements in the array, running the assigned function and provide a new array.

const apiResponse = [{
  user: {firstname: 'tolumide', lastname: 'mic'},
  birthday: 'Sun Oct 15 2017 01:00:00 GMT+0100 (West Africa Standard Time)',
  phone: 070237461283
  },
  {
  user: {firstname: 'adeotun', lastname: 'ade'},
  birthday: 'Fri Mar 15 2013 01:00:00 GMT+0100 (West Africa Standard Time)',
  phone: 08111111111
}]
const modifiedResponse = apiResponse.map(item => ({
  fullname: `${item.user.firstname} ${item.user.lastname}`,
  lastname: item.phone
}))

You should get a response like this when you print the value of modifiedResponse with console.log()

[{fullname: 'tolumide mic', birthday: '10/15/2017', phone: 070237461283}, {...}]

A good look at the example above shows that mapmethod returns a value which is assignable to a variable.

Read More Here:

  1. Array map method (MDN)
  2. ECMAScript 2020
  3. Array forEach method (MDN)

Top comments (0)