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

371
Views
I am not getting the minimum value ,it showing 0, but in case of Math.max() it showing the right maximum value, why is it so?

I'm not getting the minimum value and it shows 0 but in this case of Math.max(), it shows the right maximum value. Why is it so?

function values(ar) {
  var min_val = 0;
  for(var i = 0; i < ar.length; i++) {
    min_val = Math.min(min_val,ar[i]);
  }
  document.write(min_val);
}
values([14,99, 10, 18,19, 11, 34]);
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

It always returns 0 because you compare it to min_val. Where min_val becomes the lowest value as 0 is lower then any value in the array. Therefor min_val will always be set equal to itself and stay 0. Here is my fix :

let ar =[14,99,10,18,19,11,34]
let min_val = Math.min(...ar)
console.log(min_val)
This is also more elegant than a for-loop.

about 4 years ago · Juan Pablo Isaza Report

0

Math.min() receivec arguments like Math.min(-2, -3, -1) or with array Math.min(...arr). You are giving these arguments Math.min([14,99, 10, 18,19, 11, 34], 0) where 0 is minimum. So you are receiving 0. Also, no need for a loop as Math.min() finds the minimum. So, the solution would be:

    function values(ar) {
        var min_val = Math.min(...ar);
        //document.write(min_val);
        return min_val
    }
    console.log(values([14,99, 10, 18,19, 11, 34]))

or (to match your case)

function values(ar) {
    var min_val = Math.min(...ar);
    
    document.write(min_val);
}

in shortest form:

document.write(Math.min(...ar));
about 4 years ago · Juan Pablo Isaza Report

0

For your expected behavior, in order to find the minimum, you want to start at the absolute maximum (Infinity).

    var min_val = Infinity;
    for(var i = 0; i < ar.length; i++) {
         min_val = Math.min(min_val,ar[i]);
            }
document.write(min_val);
}
values([14,99, 10, 18,19, 11, 34]);```

This will write Infinity for empty arrays, or the minimum value for the input.

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!