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

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

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 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