Werewolf.js


#1

So I've gotten to Comparisons Operators II and up till now a lot of the script on the code editor has come up completed, not sure if this is intended or not. Usually I ignore it, clear it and write my own code. but for this specific one I'm seeing words I'm not familiar with. Namely "switch", "break", "case", "default". I've searched other forum posts and other users talk about switch as if they've used it in the past so I'm really lost here.

https://www.codecademy.com/en/courses/learn-javascript/lessons/control-flow/exercises/comparison-operators-ii


var moonPhase = 'full';
var foggyNight = false;

if (moonPhase === 'full' && foggyNight) {
  console.log('Howwlll!');
} else if (moonPhase === 'mostly full') {
  console.log('Arms and legs are getting hairier');
} else if (moonPhase === 'mostly new') { 
  console.log('Back on two feet');
} else {
  console.log('Invalid moon phase');
}

switch (moonPhase) {
 case 'full':
    console.log('Howwwwlll!!');
    break;
 case 'mostly full':
    console.log('Arms and legs are getting harrier');
    break;
 case 'mostly new':
    console.log('Back on two feet');
    break;
  default:
    console.log('Invalid moon phase');
    break;
}


#2

So, your question is how the switch works right?

The switch will check the variable inside the '()' against each of the 'case' you are defining.

In this example. Is like saying.
Ok I have this variable, is this variable equal to the case first case? (case 'full') if yes, then whatever you wrote inside the case will be executed, the break is for stop the execution of the next 'case' statements. Let's say you miss the break on one of the 'case' then all the instructions below will be evaluated as well. The default is saying, OK if nothing of the above is true, let's do this... an executes the instructions inside the default.

Your code will check the variable moonPhase against of each of the 'case' (like an if) and will execute the one that matches, if non of those match, then will do the 'default' block.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.