0

How to return value from forEach array instance?

const numArr = [10, 20, 30, 40, 50];

numArr.forEach(function (num, index, array) {
  console.log(array[index] + 100);
});

I was trying to return console.log value but it was returning last value sum.

James Z
  • 12,209
  • 10
  • 24
  • 44
  • It's not clear what you're asking. If you want to return a new array, don't use `forEach`, use `map`. – Mark Reed Sep 04 '21 at 14:47
  • @MarkReed i was experimenting with forEach, i am curious i can able to console.log bt i cannot whole array with new value. please explain why it was like that – Sairam.Gudiputis Sep 04 '21 at 14:50
  • 1
    Because that's not what `forEach` does. It runs some code for each item in the array, but throws away the results; it's purely for side effects. If you want to keep the result, use `map`. – Mark Reed Sep 04 '21 at 14:52
  • 1
    [RTM](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#return_value) – mplungjan Sep 04 '21 at 14:55
  • If you want to have the forEach process the numArray, you can let it mutate the array: `numArr.forEach(function (num, index, array) { array[index] += 100; });` – mplungjan Sep 04 '21 at 14:57

1 Answers1

0

As I can see, you want to increase every element in the array. You can do it using a map method.

const numArr = [10, 20, 30, 40, 50];

const newArr = numArr.map(v => v + 100);
console.log(newArr);
Dmytro
  • 636
  • 1
  • 3
  • 18