0

I'm trying to figure out why this code does not work

let userName = 'roy';
const userQuestion = 'Do you do CrossFit?';
userName ? console.log('Hello ' + userName + ' !') : console.log('Hello!');
console.log(`The user asked: ${userQuestion}`);
let randomNumber = Math.floor(Math.random() * 8);
let eightBall = '';
console.log(randomNumber);

switch (randomNumber) {
    case 0:
        eightBall = 'It is certain';
        break;
    case 1:
        eightBall = 'It is defidedly so';
        break;
    case randomNumber >= 1:
        eightBall = 'we cant tell';
        break;
}

console.log(` The eight ball answered: ${eightBall}`);

Trying to generate "we can tell" when the number is greater than 1 but it's not printing anything. Am I using a switch statement wrong?

2 Answers2

2

Use a default with an if statement inside like so:

let randomNumber = 100
let eightBall = ''

switch (randomNumber) {
    case 0:
        eightBall = 'It is certain';
        break;
    case 1:
        eightBall = 'It is defidedly so';
        break;
    default:
        if(randomNumber >= 1)
            eightBall = 'we cant tell';
        break;
}

console.log(` The eight ball answered: ${eightBall}`);
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338
  • Given OP's code `randomNumber` will never be negative and the test `if(randomNumber >= 1)` is redundant, it will always be true – phuzi Apr 17 '18 at 15:15
2

case takes an argument to be equal too, not a boolean expression. You could just use the default branch:

switch (randomNumber) {
    case 0:
        eightBall = 'It is certain';
        break;
    case 1:
        eightBall = 'It is defidedly so';
        break;
    default: // Here!
        eightBall = 'we cant tell';
        break;
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350