Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

178
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda