Magic Eight Ball exercise - How to rewrite using switch statements

Hi Everyone.

First off I’m new here so sorry if this is a rookie question, but I’m working on the JavaScript Magic Eight Ball exercise, but have only done it using long hand ‘if…else’ and ‘else if’ statements. Could someone please advise how I could rewrite this with switch statements?

Also what is the real world advantage of using switch statements? Is it just time saving for writing the code or does it have a processing advantage too?

I’ve put a copy of the code below:

let eightBall = ''; 
if(randomNumber === 0) {eightBall = 'It is certain'
;}
else if(randomNumber === 1) {
  eightBall = 'It is decidedly so';
} 
else if(randomNumber === 2) {
  eightBall = 'Reply hazy try again';
} 
else if(randomNumber === 3) {
  eightBall = 'Cannot predict now';
} 
else if(randomNumber === 4) {
  eightBall = 'Do not count on it';
} 
else if(randomNumber === 5) {
  eightBall = 'My sources say no';
} 
else if(randomNumber === 6) {
  eightBall = 'Outlook not so good';
} 
else 
{
  eightBall = 'Signs point to yes';} 

The switch statement is in my opinion simpler than if and else statements. So, instead of typing randomNumber === 0, you can type case 0.

Remember that switch statements need break in the block of code of each case so whenever you meet the case, the program breaks from the statement and continues to run the rest of your code. Finally, like if and else has the else, switch has the default keyword.

So in your example it should work like this:

switch(randomNumber){
  case 0:
   eightBall = 'It is certain';
   break;
  case 1:
   eightBall = "It is decidedly so";
   break;
  default:
    eightBall = "Signs point to yes";
    break;
}

Also to answer your second question, the performance it’s microscopic at this level. However in terms of readability the switch statement is a lot better.

2 Likes

Once you learn to work with Arrays in the next lessons you will see there is an even simpler way to implement this with a lot less repeated code.

Once you complete the Arrays module, come here and this solution will make more sense to you:

const randomNumber = Math.floor(Math.random() * 8);

const responses = [
  'It is certain',
  'It is decidedly so',
  'Reply hazy try again',
  'Cannot predict now',
  'Do not count on it',
  'My sources say no',
  'Outlook not so good',
  'Signs point to yes',
];

const eightBall = responses[randomNumber];

console.log(`MagicBall: ${eightBall}`);

Like the case of the switch statements improving the readability over if statements, one key goal is to make your code as readable as possible with the simplest solution, so it is easy to be maintained by future developers or future you. Too many if else statements (especially nested if statements inside if statements) make it very hard for the brain to follow all the paths your logic may take.

3 Likes

Thanks both for your help with this one.

I’ll have another look at this array solution when I get to that section of the material as you say.

1 Like

https://www.codecademy.com/paths/full-stack-engineer-career-path/tracks/fscp-javascript-syntax-part-i/modules/fecp-learn-javascript-syntax-conditionals/projects/magic-eight-ball-1

I did a thing (kinda)! I was messing around with whether or not you could console.log() a switch statement, since you can console.log() a ternary operator. I realized you couldn’t do that straight up, but that you could turn the eightBall into a function using ES6-style anonymous arrow functions and then call it:

let eightBall = () => {
    switch (randomNumber) {
        case 0:
            return 'I don\'t think so'
        etc.
}}

console.log(eightBall())

This was cool because then I was able to refactor out repeated use of console.log() calls and isolating the function is good coding practice. But I had an error in my original implementation because of a lack of a curly bracket. When looking up the answer, I stumbled upon this S.O. question: switch unexpected token in javascript - Stack Overflow

The first answer shows how you can get rid of the need for “break;”, but then also shows that through the clever use of an array, you can actually refactor the code even further and get rid of the switch function entirely. Applied to the Eight Ball project, you can do this:

let eightBall = {
  0: 'It is certain',
  1: 'It is decidedly so',
  2: 'Reply hazy try again',
  3: 'Cannot predict now',
  4: 'Do not count on it',
  5: 'My sources say no',
  6: 'Outlook not so good',
  7: 'Signs point to yes',
}

console.log(eightBall[randomNumber])

I know the point of the Eight Ball project is to apply conditionals, but this is just so readable and cool. I couldn’t not share it!

1 Like