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

311
Vistas
Using switch(true) in javascript for case with number range not working?

My goal is to store variable greet with "Good AM" if between midnight and 12PM. or "Good Afternoon" if between 12PM and 6PM. or "Good evening" if between 6PM and midnight.

I've attached my code at bottom. The problem is, it always return the result of greet = "Good AM", even though it's not morning/fall in to the range specify in this case.

I found that there is something wrong with case (0 < timeNow <= 12) part as I have modified my code to replace case (0 < timeNow <= 12) using case(timeNow<=12) and it works. Does anyone know why this happen?

p/s: I also noticed warning of 'Unexpected mix of '<' and '<='. (no-mixed-operators)eslint' in my code sandbox.

const timeNow = new Date('8-26-2021 23:15:00').getHours();
console.log(timeNow);

switch (true) {
  case (0 < timeNow <= 12):
    greet = "Good AM";
    break;
  case timeNow <= 18:
    greet = "Good Afternoon";
    break;
  case timeNow <= 23:
    greet = "Good Evening";
    break;

  default:
    greet = "error";
}
console.log(greet);

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

This condition doesn't mean what you think it means:

0 < timeNow <= 12

For example, if the first condition resolves to true then the rest of the condition is:

true <= 12

Which doesn't make much sense. Expressions are logical, not intuitive. If you want to check two separate things, write two separate expressions and combine them with a logical operator:

0 < timeNow && timeNow <= 12
over 4 years ago · Santiago Trujillo Denunciar

0

Like @David said... Here's a snippet with a hard-coded time for demonstration purposes along with the corrected comparison in the first case statement:

const timeNow = new Date('8-26-2021 23:15:00').getHours();
console.log(timeNow);

switch (true) {
  case (timeNow <= 12):
    greet = "Good AM";
    break;
  case timeNow <= 18:
    greet = "Good Afternoon";
    break;
  case timeNow <= 23:
    greet = "Good Evening";
    break;

  default:
    greet = "error";
}
console.log(greet);

over 4 years ago · Santiago Trujillo 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