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

144
Visualizações
Array sorting and global variable scope in JavaScript

I'm trying to sort an array into a new sorted array.

const a = [25, 15, 30, 50, 45, 20];

let cheap = 0;
let ordered = [];

const listLength = a.length;

for (let atual = 0; atual < listLength; atual++) {
    Ordenador(a);
}

function Ordenador(arr){

    // let cheap = 0;

    for (let i = 0; i < arr.length; i++) {
        if(arr[i] < arr[cheap]) {
            cheap = i;
        }
    }
    ordered.push(arr[cheap]);
    arr.splice(cheap,1);
}

If I make the cheap variable global, the new return array is

[ 15, 20, undefined, undefined, undefined, undefined ]

but when cheap variable is inside of the function it works as expected!

I don't understand why it doesn't work when the cheap variable in in the global scope.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Because, in the loop, cheap changes to 0 in your local variable case and in the case of global one. It doesn't change to 0. Hence, you're getting undefined in your array

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