Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

136
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!