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

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

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 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