Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

375
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda