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

201
Vistas
Javascript reassigning array value no longer references?

Not sure how else to explain the question. Here is some very simple code to demonstrate it though.

I would expect testValue and testValue2 to be [20, 21, 22], since they are passed by reference and not passed by value, as far as I understand it, and as far as it looks like since they update with the .push() method.

Does anyone know what is happening here? Why do both testValue and testValue2 seem to start passing by value after we reassign the original array?

let testArray = [1, [10, 11, 12], 3, 4, 5];
let testValue = testArray;

testArray.push(13);
testArray = [20, 21, 22];

console.log(testArray);
console.log(testValue);


//Different attempt
let testArray2 = [1, [10, 11, 12], 3, 4, 5];
let testValue2 = testArray2[1];

testArray2.push(13);
testArray2[1] = [20, 21, 22];

console.log(testArray2);
console.log(testValue2);

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

0

problem: location memory.

you create new variable testValue with testArray, this 2 variable have same location memory, then you use .push() it will push new value to location memory of variable, not depend of the array you use it.

if you not want they same location memory. use this:

// Array.from
let testArray = [1, [10, 11, 12], 3, 4, 5];
let testValue = Array.from(testArray);

// spread operator
let testArray = [1, [10, 11, 12], 3, 4, 5];
let testValue = [...testArray];

for more detail check this article:

  1. https://backbencher.dev/articles/javascript-variables
  2. https://medium.com/@ethannam/javascripts-memory-model-7c972cd2c239
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