Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

309
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!