ShueiYang
ShueiYang

Reputation: 808

Problem when learning forEach method in Javascript

I start learning Javascript since a week and I try to do some practice about the loop, So I try to make a function which each time I call it, I doubled the numbers in an array.

I manage to do it with the classic "for" loop like this as an example:

var numbers = [2, 5, 37, 500, 75]; 

function getDoubled() {
  for (var i = 0; i < numbers.length; i++) {
    (numbers[i] = numbers[i] * 2);
  }
}

So here the numbers in my array doubled each time I call the function getDoubled(); and now I try to do the same with forEach method.

var numbers = [2, 5, 37, 500, 75];

function getDoubled(array) {
  array.forEach(function(number) {
    (number = number * 2);
  })
}

But I wasn't able to change the array when I call the function getDoubled(numbers), however if I test with console.log(number*2), it worked in the console, so I wasn't able to figure it out the mistake.

Upvotes: 1

Views: 149

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371233

Reassigning an identifier has no side-effects. That is, doing someVariable = somethingNew will only result in a discernable change in how your script runs if something else references the someVariable which has the new value in it. Here, the number = number * 2 does nothing because nothing is referencing the doubled number variable; reassigning the parameter doesn't do anything to the array.

The way to do this with forEach would be to reassign the index in the array, just like in the for loop.

var numbers = [2,5,37,500,75];
function getDoubled(array) {
    array.forEach(function(number, i){
        array[i] = number * 2;
    })
}
getDoubled(numbers);
console.log(numbers);

Alternatively, a nicer approach would be to construct a new array with the changed values, which can be done with .map, which creates a new array by performing a callback on every element of the original array - that way you don't have to look at the (unimportant) indicies to get the output you want.

var numbers = [2,5,37,500,75];
function getDoubled(array) {
    return array.map(num => num * 2);
}
console.log(getDoubled(numbers));

Upvotes: 6

Related Questions