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

200
Vistas
JavaScript forEach: mutate elements

I want to use forEach on an array. Since forEach is a mutator, it should mutate the values in the original array, but it's not. What's the issue here?

let array = [1, 2, 3, 4]; //simple array declaration

array.forEach((ele) => ele * 2); //using forEach to double each element in "array"

console.log(array); //logs [1,2,3,4] instead of [1,4,6,8]

What's going on here?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

No, forEach does not mutate the original array.

You can achieve what you are looking for by giving a second parameter of index, then updating the values of the original array.

let array = [1, 2, 3, 4];
array.forEach((ele, index) => array[index] = ele * 2);

console.log(array);

documentation for forEach

about 4 years ago · Juan Pablo Isaza Denunciar

0

Array#forEach callback has second and third optional parameters that you can use to access and mutate each element:

index [Optional]: The index of element in the array.

array [Optional]: The array forEach() was called upon.

const array = [1, 2, 3, 4];

array.forEach((_, index, arr) => arr[index] *= 2);

console.log(array);

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