Example of array forEach in JavaScript

forEach() in JavaScript [with Examples]

The JS forEach method calls the provided callback function once for each element of an Array.

forEach Syntax

Here is the full syntax:

array.forEach(callback(element, index, array), thisArg)

My purpose with this article is that you learn the most common uses of forEach, so I will explain how to use it with a simplified syntax.

array.forEach(callback(element, index))

callback function: the function to call on each element of the array. The callback function can receive up to 3 arguments, but the 2 most frequently used are:

  • element: the value of the current element
  • index: the index of the current element

How to use forEach – basic example

Here’s an easy-to-understand example to illustrate how forEach works. One of the simplest uses of forEach is to display each element of an Array to the console.

const fruits = [
  'Banana', 
  'Grape', 
  'Peach',
  'Apple', 
  'Strawberry'
];

fruits.forEach(function(item, index) {
  console.log(`The value ${item} is in index ${index}`);
});

// The result is:
// The value Banana is in index 0
// The value Grape is in index 1
// The value Peach is in index 2
// The value Apple is in index 3
// The value Strawberry is in index 4

forEach always returns undefined

The value that forEach returns is undefined. It is important that you are aware of this fact, otherwise you may encounter unexpected results.

Try to identify the problem in the following example:

let numbers = [1, 2, 3, 4, 5];

const doubles = numbers.forEach(function(num) {
  return num * 2;
});

console.log(doubles);

What value do you expect to find in the variable doubles? The value is not an array with [2, 4, 6, 8, 10].

If you try to execute this code snippet, you will see undefined being displayed to the console. The reason? forEach always returns undefined.

forEach skips empty spaces

In the following example, pay special attention to “empty spaces”, that is, where there are 2 commas in a row , , In the following array we have 2 empty spaces.

const languages = ['javascript', ,'python', , 'ruby'];

languages.forEach(function(lenguage) {
  console.log(lenguage);
});

// The result is:
// javascript
// python
// ruby

We execute a function per iteration. With the array in languages, upon reaching the second element, forEach skips it. And the same is done with the fourth element.

Use forEach on Objects in JavaScript

You can iterate over an Object with forEach. More specifically, you can iterate over an Object’s keys, values, or both keys and values.

Let’s see an example of each.

Using forEach to iterate over an Object’s keys 🗝️

You can get an array of the object’s keys using the Object.keys method. The Object.keys method returns an array of the object’s enumerable properties.

const obj = {
  name: 'Leo',
  business: 'ABC Company',
  position: 'Software Engineer'
};

Object.keys(obj).forEach(function (key) {
  console.log(`The value ${obj[key]} is in key ${key}`);
});

// The result is:
// The value Leo se encuentra is in key name
// The value ABC Company is in key business
// The value Software Engineer is in key position

This code snippet extracts the value of each property using all the object’s keys and iterating over them using forEach and prints it on the console.

Using forEach to iterate over an Object’s values

You can get an array of the values in the object using the Object.values method. The Object.values method returns an array of the object’s enumerable property values.

const obj = {
  name: 'Leo',
  business: 'ABC Company',
  position: 'Software Engineer'
};

console.log(Object.values(obj)); // ['Leo', 'ABC Company', 'Software Engineer']

Object.values(obj).forEach(function (value) { 
  console.log(value); // ✅ Leo, ABC Company, Software Engineer
});

Using forEach to iterate over an Object’s keys and values

The Object.entries method returns an array of arrays with the object’s keys and values. Each “entry” is an array with 2 items, where the item with index 0 is the key and the item with index 1 is the value. Refer to the code snippet below:

const obj = {
  name: 'Leo',
  business: 'ABC Company',
  position: 'Software Engineer'
};

console.log(Object.entries(obj)); 

// The result is
// [
//   ['name', 'Leo'],
//   ['business', 'ABC Company'],
//   ['position', 'Software Engineer']
// ]

Troubleshooting forEach 🐛

If forEach is not used correctly, we may encounter some errors. Here are some of the most common mistakes when using forEach.

Uncaught TypeError: obj.forEach is not a function ❌

The Uncaught TypeError: obj.forEach is not a function error occurs when you try to use the forEach() method on something that is not an array.

You may have something similar to this:

const obj = {
  name: 'Leo',
  business: 'ABC Company',
  position: 'Software Engineer'
};

obj.forEach(function (elem) {
  console.log(elem);
});

// Throws an error
// Uncaught TypeError: obj.forEach is not a function ❌

Can you identify the bug on the code?

We are trying to call forEach on an object. The same would happen if you tried to call forEach on a string or a boolean value.

How can this error be resolved? ✅

If you tried to call forEach on an object, you may have meant to iterate over the object’s properties. If this is the case, apply the Object.keys method as follows:

const obj = {
  name: 'Leo',
  business: 'ABC Company',
  position: 'Software Engineer'
};

console.log(Object.keys(obj)); // ['name', 'business', 'position']

Object.keys(obj).forEach(function (key) {
  console.log(key); // ✅ name, business, position
});

For proper use of forEach on objects, please refer to the section Use forEach on Objects in JavaScript.

Uncaught TypeError: Cannot read properties of undefined (reading forEach) ❌

The Uncaught TypeError: Cannot read properties of undefined (reading 'forEach') error occurs when you try call the forEach() method on undefined.

Here’s an example of how this error can happen:

let arr;

arr.forEach(function (elem) {
  console.log(elem);
});

// Throws the error
// Uncaught TypeError: Cannot read properties of undefined (reading 'forEach') ❌ 

Can you recognize the problem?

The variable arr has the value undefined.

Similar Posts