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.


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

if (moonPhase === 'full' && foggyNight) {
} 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':
 case 'mostly full':
    console.log('Arms and legs are getting harrier');
 case 'mostly new':
    console.log('Back on two feet');
    console.log('Invalid moon phase');


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.


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