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

92
Views
why JavaScript is behaving differently

why it is showing me 36 even though the minimum number is 27

   var combination = [27, 36]
    
    for (let x in combination) {
        if (combination[x] < 50) {
            var min = Math.min(combination[x])
        }
    }
    
    console.log(min)

i tried this multiple ways like

    var combination = [27, 30, 40, 44, 3, 239, 329, 2, 5, 20923, 96]
    
    for (let x in combination) {
        if (combination[x] < 50) {
            var min = Math.min(combination[x])
        }
    }
    
    console.log(min) //output--  5         //it should be 2

in this third example i add (-) to 2

var combination = [27, 30, 40, 44, 3, 239, 329, -2, 5, 20923, 96]

for (let x in combination) {
    if (combination[x] < 50) {
        var min = Math.min(combination[x])
    }
}

console.log(min) // output-- still 5     // it should be -2 

again when am adding (-) to other numbers like in -96 or -5 the output was okay (-96) but when im adding (-) to 2 it is not showing me -2 in the output instead it showing me 5

not only in javascript i tried this with lua, php but output was same as js

can anyone explain me why this happen and how solve this

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You're not comparing values to determine the minimum, but instead just replacing the min variable with the last number in the array that is smaller than 50. This can be fixed as follows:

let min = undefined;
for (let x in combination) {
    if (combination[x] < 50) {
        min = min == undefined ? combination[x] : Math.min(min, combination[x])
    }
}

Using filter and reduce, this can be made a lot shorter:

combination.filter(x => x < 50).reduce((x, y) => Math.min(x, y))
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!