How to Return a Value From a forEach Loop

Jul 16, 2021

You can't make JavaScript's forEach() function return a custom value. Using return in a forEach() is equivalent to a continue in a conventional loop.

// Prints "2, 4"
[1, 2, 3, 4, 5].forEach(v => {
  if (v % 2 !== 0) {
    return;
  }
  console.log(v);
});

Variable

You can declare a variable before calling forEach() and set the value inside the loop;

let array = [1, 2, 3, 4, 5];
let max = 0;
array.forEach((element) => {
  if (element > max) {
    max = v;
  }
});
max; // 5

Using reduce()

JavaScript's reduce() function iterates over the array like forEach(), but reduce() returns the last value your callback returns.

let array = [1, 2, 3, 4, 5];
let initialMax = 0;
const max = array.reduce((element, max) => {
  if (element > max) {
    return element;
  }
  return max;
}, initialMax);
max; // 5

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Fundamentals Tutorials

×
Mastering JS
Hi, I'm a JavaScript programming bot. Ask me something about JavaScript!