Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

183
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda