JAVASCRIPT

JavaScript forEach(): Syntax, Usage, and Examples

The forEach() method in JavaScript provides a clean, readable way to loop through elements in an array. It's one of the most commonly used iteration methods in modern JavaScript and is essential for beginners learning web development.

The JavaScript forEach method executes a provided callback function once for each array element, allowing you to work with data without writing traditional for or while loops. Unlike some array methods, forEach() doesn't return a return value.

Quick Answer: How to Use forEach() in JavaScript

The forEach() method executes a function once for each element in an array, in order. It's a simple way to iterate over an array without needing a classic for loop. Its main purpose is to perform an action for each element (a "side effect"), as it does not return a new array.

Syntax (using an arrow function):

array.forEach((element, index) => {
  // Code to run for each element
});

Example:

const fruits = ['apple', 'banana', 'cherry'];

fruits.forEach((fruit, index) => {
  console.log(`Fruit at index ${index}: ${fruit}`);
});

// Output:
// Fruit at index 0: apple
// Fruit at index 1: banana
// Fruit at index 2: cherry

Use forEach() when you want to do something with each element, not when you want to create a new array from the existing one.

How to Use JavaScript forEach

The forEach() method works on arrays and array-like structures. The syntax looks like this:

array.forEach(function(currentValue, index, array) {
  // Your code here
});

You can also use an arrow function for brevity:

array.forEach((currentValue, index, array) => {
  // Your code here
});

Parameters:

  • currentValue – Required. The current element of the array being processed.
  • index – Optional. The index of the current element.
  • array – Optional. The array that forEach() is being called on.

The method also accepts an optional thisArg parameter to set the this value inside the callback function.

Basic Example:

const fruits = ["apple", "banana", "cherry"];

fruits.forEach((fruit) => {
  console.log(fruit);
});

This prints each fruit to the console—one per line.

When to Use forEach JavaScript

Use the JavaScript forEach method when you need to:

Perform Side Effects for Each Item in an Array

forEach is ideal when you want to log data, update the DOM, or perform other side effects. It doesn’t return a value, so don’t use it when you need to create a new array.

const users = ["Alice", "Bob", "Charlie"];

users.forEach((user) => {
  console.log(`Welcome, ${user}!`);
});

Loop Over an Array Without Managing Indexes Manually

Unlike a traditional for loop, you don’t need to declare counters or check lengths manually:

const scores = [92, 85, 74];

scores.forEach((score, index) => {
  console.log(`Score #${index + 1}: ${score}`);
});

This makes code shorter and easier to read.

Work with JavaScript Arrays Functionally

forEach provides a functional programming pattern. It’s not as powerful as map() or filter(), but it’s perfect when you want to apply logic to each item without changing the original array.

Examples of JavaScript forEach Loop in Practice

Looping Over a JavaScript Array

const colors = ["red", "green", "blue"];

colors.forEach((color) => {
  document.body.style.backgroundColor = color;
});

This changes the background color sequentially (only the last color will persist). This pattern is useful for updating HTML elements dynamically.

Using Index and Original Array

const names = ["John", "Jane", "Jim"];

names.forEach((name, index, arr) => {
  console.log(`${name} is at position ${index} in [${arr}]`);
});

forEach gives access to all the context you might need.

JavaScript Array forEach with Objects

const students = [
  { name: "Emma", grade: "A" },
  { name: "Liam", grade: "B" }
];

students.forEach((student) => {
  console.log(`${student.name} received grade ${student.grade}`);
});

This is useful when looping through arrays of objects, especially in React applications.

Learn More About the forEach Loop in JavaScript

JavaScript forEach Index Handling

You can always access the current index through the second parameter:

const cities = ["Paris", "Tokyo", "Sydney"];

cities.forEach((city, index) => {
  console.log(`City ${index + 1}: ${city}`);
});

This is helpful for numbered lists or position-based logic.

Using forEach Loop in JavaScript with Conditional Logic

const numbers = [5, 10, 15, 20];

numbers.forEach((num) => {
  if (num > 10) {
    console.log(`${num} is greater than 10`);
  }
});

You can apply any if/else logic directly inside the callback.

Using continue in JavaScript forEach

Unlike traditional loops, you can't use continue inside forEach(). Instead, simulate it with return inside the callback:

const animals = ["cat", "", "dog"];

animals.forEach((animal) => {
  if (!animal) return;
  console.log(animal);
});

The return skips over the current iteration without stopping the entire loop.

forEach vs Map in JavaScript

Use forEach() when you're executing side effects and don’t need to return anything. Use map() when you want to create a new array:

// forEach
const names = ["Anna", "Ben"];
names.forEach((name) => console.log(name.toUpperCase()));

// map
const upperNames = names.map((name) => name.toUpperCase());
console.log(upperNames); // ["ANNA", "BEN"]

They serve different purposes. Choosing between them depends on your intent.

forEach on Objects

JavaScript forEach doesn’t work directly on plain objects. To loop through object properties, use Object.keys() or Object.entries():

const person = { name: "Alex", age: 30 };

Object.entries(person).forEach(([key, value]) => {
  console.log(`${key}: ${value}`);
});

This makes it behave similarly to iterating over a key-value map.

JavaScript Map forEach

If you're working with a Map object instead of an array, Map.prototype.forEach() works slightly differently:

const capitals = new Map([
  ["France", "Paris"],
  ["Japan", "Tokyo"]
]);

capitals.forEach((value, key) => {
  console.log(`${key}'s capital is ${value}`);
});

Notice how the callback parameters are value, key, unlike arrays which use element, index.

forEach and Arrow Functions

Arrow functions work great with forEach for cleaner code:

[1, 2, 3].forEach((num) => console.log(num));

But remember, arrow functions don’t bind their own this, so if you rely on this inside the loop, use a regular function or bind manually.

Error Handling with forEach

Wrap the logic inside the callback with a try-catch block to handle exceptions:

data.forEach((item) => {
  try {
    riskyFunction(item);
  } catch (error) {
    console.error("Error processing item:", error);
  }
});

This prevents one bad item from crashing the entire loop.

The JavaScript forEach method is a convenient way to iterate over arrays and apply logic to each item. Whether you're looping over data for display, executing side effects, or processing arrays of objects, foreach JavaScript syntax keeps your code concise and readable. It doesn’t return a new array like map(), but it excels when the goal is to act on data directly.

Key Takeaways for JavaScript forEach()

  • No Return Value: forEach() always returns undefined. Its purpose is to execute a function for each element, not to create a new array.
  • Use for Side Effects: It is the ideal choice for actions like logging to the console, updating a variable outside the loop, or changing the DOM.
  • Cannot be Stopped: You cannot use break or continue to exit or skip iterations in a forEach() loop. A return statement inside the callback will only exit the current iteration, not the entire loop.
  • Use map() for Transformation: If your goal is to create a new array based on the values of an existing array, use the map() method instead.
  • Readable and Concise: It offers cleaner syntax than a traditional for loop, as you don't need to manage an index counter.
Learn to Code in JavaScript for Free
Start learning now
button icon
To advance beyond this tutorial and learn JavaScript by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2025 Mimo GmbH

Reach your coding goals faster