Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

177
Views
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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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));

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!