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

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

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

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