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

86
Vistas
Why is array destructuring not working in this case?

I am trying to swap members of arr. But I am getting [0, 0] as output. I am expecting [1, 0].

const arr = [0, 1];
[arr[1],arr[0]] = arr;
console.log(arr)

But while doing this, it outputs [1, 0] which I think I understand.

const arr = [0, 1];
[arr[1],arr[0]] = [arr[0], arr[1]];
console.log(arr)

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

0

Your first example is both modifying the array arr points to and getting its values from that same array, as though you did this:

const arr = [0, 1];
// Here, `arr` is `[0, 1]`
arr[1] = arr[0];      // <=== Changes `arr[1]`...
// Now, `arr` is `[0, 0]`
arr[0] = arr[1];      // <=== ...so the new value of `arr[1]` is used here.
// Still `[0, 0]`

Your destructuring is doing the same thing: Using arr[1] after it's been changed by the destructuring assignment.

Your second example is modifying the array arr points to, but only after getting the old values from the array into a new array:

const arr = [0, 1];
const newArray = [arr[0], arr[1]];
// Here, `arr` is `[0, 1]`, `newArray` is `[0, 1]`
arr[1] = newArray[0]; // <=== Changes `arr[1]`...
// Here, `arr` is `[0, 0]`, `newArray` is still `[0, 1]`
arr[0] = newArray[1]; // <=== ...but that doesn't affect `newArray[1]`, so this works.
// Here, `arr` is `[1, 0]`, `newArray` is still `[0, 1]`

That works, because even though arr[1] was changed by the destructuring assignment, the new value for arr[0] isn't coming from arr[1], it's coming from newArray[1].

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