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

270
Visualizações
Switch statement within function returns "undefined" for no obvious reason

I am trying to create a simplistic function which uses a switch statement to return a weighted number. For my use case, the solution is most befitting, however I am getting "undefined" as the result for no obvious reasons. If anyone could point out the mistake, I'm making.

function randomCase() {
  let n = Math.floor(Math.random() * 100);

  switch (n) {
    case n < 70:
      return 1;
    case n < 80:
      return 2;
    case n < 90:
      return 3;
    case n < 100:
      return 4;
  }
}

temp = randomCase();

console.log(temp);

I tried to debug with Chrome developer tool and figure out what might be causing this, but of no avail. It seems there is something obvious I'm missing. (Still learning JS)

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

As VLAZ mentioned in the comments, a switch statement checks for equality.

You'll want to use an if statement instead:

function randomCase() {
  let n = Math.floor(Math.random() * 100);

  if (n < 70) {
    return 1;
  } else if (n < 80) {
    return 2;
  } else if (n < 90) {
      return 3;
  } else if (n < 100) {
      return 4;
  }
}

temp = randomCase();

console.log(temp);

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