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.
Asked
Active
Viewed 1.6k times
-2
-
2What have you tried so far? Please post an example of what you've tried. – CF256 Aug 22 '17 at 15:24
-
`forEach` is not _a syntax_, it is a `method` of `Array`. – lilezek Aug 22 '17 at 15:24
-
refer this : https://stackoverflow.com/a/12482991/1531476 – Ankit Aug 22 '17 at 15:25
-
"How do you use forEach to increment each value..." - you don't. You're looking for `.map`. – georg Aug 22 '17 at 15:36
3 Answers
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
-
What does **a => a** do? I've seen the arrow function before, but what do the a's represent? – JohnDoe99 Aug 22 '17 at 17:45
-
1
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