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



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source