Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

373
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda