1

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);
Rob Moll
  • 3,345
  • 2
  • 9
  • 15
Yu Hien Ng
  • 45
  • 6

2 Answers2

2

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
David
  • 208,112
  • 36
  • 198
  • 279
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);
Rob Moll
  • 3,345
  • 2
  • 9
  • 15