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

134
Vistas
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 Respuestas
Responde la pregunta

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