1

Here is my code

var randomNumber = Math.ceil(100 * Math.random());

switch (randomNumber) {
case (randomNumber < 20):
    console.log("The number is less than 20");
    break;
case (randomNumber => 20 && randomNumber < 50):
    console.log("The number is between 20 and 50");
    break;
case (randomNumber => 50 && randomNumber < 75):
    console.log("The number is between 50 and 75");
    break;
default:
    console.log("The number is greater than 75");
    break;
}

console.log(randomNumber);

The first part simply declares a new binding and assigns it a random integer value between 1 and 100.

The second part, the switch statement, is supposed to send a particular message, depending on the condition, the value of the randomNumber binding.

For some reason--I'm not sure why--it only executes the code corresponding to the default keyword. And, of course, it also executes the last statement, which prints the value of the binding to the browser console.

What am I doing wrong?

Custer
  • 119
  • 1
  • 8
  • Here is the description of the [Javascript switch statement](https://www.w3schools.com/js/js_switch.asp). Check the part under *This is how it works:...*. – lurker Dec 29 '19 at 20:08
  • As Nina mentions, you're treating `switch` as if it were if/else if conditional blocks – Andrew Dec 29 '19 at 20:09
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch – Scott Marcus Dec 29 '19 at 20:11
  • See [this SO answer](https://stackoverflow.com/questions/5619832/switch-on-ranges-of-integers-in-javascript) to understand what Nina is suggesting. – RamblinRose Dec 29 '19 at 20:12

1 Answers1

3

The switch statement uses a strict comparison and you need to check against true.

Then you could check only the upper bound, because you checked already the lower one.

var randomNumber = Math.ceil(100 * Math.random());

switch (true) {
    case randomNumber < 20:
        console.log("The number is less than 20");
        break;
    case randomNumber < 50:
        console.log("The number is between 20 and 50");
        break;
    case randomNumber < 75:
        console.log("The number is between 50 and 75");
        break;
    default:
        console.log("The number is greater than 75");
        break;
}

console.log(randomNumber);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • 1
    But really, if this is the scenario, an `if` is probably the better construct to use. – Scott Marcus Dec 29 '19 at 20:11
  • @ScottMarcus, it really depends, if only a value has to be returned, or some more statements have to ecexuted, ... – Nina Scholz Dec 29 '19 at 20:20
  • I'm actually reading Eloquent JavaScript, and the author seemed to imply that the if statement and the switch statement were interchangeable. It seems there is more nuance. Thanks, Nina! (-: – Custer Dec 29 '19 at 20:24