Magic Eight Ball - why do i need to include 'break' in switch statement?

Hi there,

I’m working on https://www.codecademy.com/courses/introduction-to-javascript/projects/magic-eight-ball-1.

I’m just wondering why I need to include a ‘break’ statement in each case of the switch statement?
Currently, when I try to run the following code, ‘Signs point to yes’ is always assigned to ‘eightBallSwitch.’ But wouldn’t randomNumber only have one value assigned to it? Why is ‘case: 7’ run?

let userName = 'Anonymous';

userName ? console.log(`Hello, ${userName}!`) : console.log('Hello!');

let userQuestion = 'Will someone bring me pizza?';

console.log(userName + ': ' + userQuestion);

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

// An eightball variable to be assigned with a switch statement.

let eightBallSwitch = ''

switch (randomNumber) {
  case 0:
    eightBallSwitch = 'Not a chance';
  case 1:
    eightBallSwitch = 'Peut-être';
  case 2:
    eightBallSwitch = 'Fat chance';
  case 3:
    eightBallSwitch = 'Yes, maybe';
  case 4:
    eightBallSwitch = 'Definitely';
  case 5: 
    eightBallSwitch = 'You got it';
  case 6: 
    eightBallSwitch = 'Mmhmm';
  case 7:
    eightBallSwitch = 'Signs point to yes';
} 

console.log(`The answer is: ${eightBallSwitch}`);

// eightBall for if/else if statement

let eightBallIf = ''

// else statement not mandatory

if (randomNumber === 0) {
  eightBallIf = 'Not a chance';
} else if (randomNumber === 1) {
  eightBallIf = 'Peut-être';
} else if (randomNumber === 2) {
  eightBallIf = 'Fat chance';
} else if (randomNumber === 3) {
  eightBallIf = 'Yes, maybe';
} else if (randomNumber === 4) {
  eightBallIf = 'Definitely';
} else if (randomNumber === 5) {
  eightBallIf = 'You got it';
} else if (randomNumber === 6) {
  eightBallIf = 'Mmhmm';
} else if (randomNumber === 7) {
  eightBallIf = 'Signs point to yes';
}

console.log(`The answer is: ${eightBallIf}`);

Thanks!

There’s a thing called fall-through for switch statements,
meaning that if you don’t exit out of the switch block using break (or something else)
then the cases afterward will also be executed.

1 Like

So if randomNumber was 4, the switch block would assign ‘eightBallSwitch’ the value in case 4, then 5, then 6, then 7. Thank you! I understand now :slight_smile: