-2

How do you use the forEach method in Javascript to increment each value in the array by 5? Can someone please give me an example, I'm confused on how to use the syntax for forEach in this situation.

Erazihel
  • 7,295
  • 6
  • 30
  • 53
JohnDoe99
  • 89
  • 2
  • 2
  • 4

3 Answers3

9

You should use the Array#map function instead of forEach to increment all the values of your array by 5:

const array = [1, 2, 3, 4];

const result = array.map(a => a + 5);

console.log(result);
Erazihel
  • 7,295
  • 6
  • 30
  • 53
1

map() is a better option in this case . see the below sample and fiddle

var numbers = [1, 5, 10, 15];
var newnum = numbers.map(function(x) {
   return x + 5;
});
console.log(newnum);

or you can also use arrow function syntax for ES2015

var numbers = [1, 5, 10, 15];
 var newnum = numbers.map(x => x + 5);
console.log(newnum);

link to fiddle : https://jsfiddle.net/vjzbo9ep/1/

Niladri
  • 5,832
  • 2
  • 23
  • 41
1

If the goal is to apply Array.forEach function to increment each value in the array by 5 while modifying the initial array in-place, use the following:

var arr = [2, 3, 4];
arr.forEach(function(v, i, a){ a[i] += 5; });

console.log(arr);
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105