Home > Mobile >  Array sorting and global variable scope in JavaScript
Array sorting and global variable scope in JavaScript

Time:02-28

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.

CodePudding user response:

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

  • Related