Doubt over the function break


#1

Hi ,
In the switch statements section and in course 7/8,I have a doubt . Can you please elaborate on this sentence as i cannot understand break, the code is available in course 7/8.


So here is the statement:

’ The program stops with the break keyword. This keyword will prevent the switch statement from executing any more of its code.’


This is one of my doubt.

The second one would be:

var moonPhase = 'full';

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

Why is this code not correct ,I understand all the four sentences jam up together but why does it do like that ,isn’t it supposed to work when the subsequent case’…’ is called upon?

Thnx


#2

The ‘break’ keyword in the switch avoid the execution of all the other ‘case’. i.e.
In this particular example.
Your moonPhase is full. This matches the first case, and the console.log(‘Howwwwlll!!’) will be executed, since there is no ‘break’ keyword, all the other ‘case’ will be executed as well. If you add the ‘break’ right below the statements that you want to execute if the case matches, only the case’full’ statements will be executed, once it has been executed, the switch will be over and the program execution will continue.

Let’s say your moonPhase is ‘mostly full’. This matches the second case, so, the mostly full, mostly new and default statements will be executed (without the break keyword).
Otherwise, only the mostly full case will be executed, and the program will continue.

Hope this helps!


#3

Thanks for your answer .I still didn’t get a part of it.Why does it do like that?If case'full' is called upon why does it display all the sentences.
Regards


#4

Because there are no breaks.

switch(expression) {
case value:
    break;
}

#5

I mean why does it display all the sentences if there are no brake’s.Because shouldn’t it display only when the next case (s) is called upon?I am sorry if i am troubling you but i seriously can’t get this one.
Thanks


#6

It’s the nature of the language to display all the cases if no breaks are inserted. It ignores the cases and renders the statements.


#7

Ok ,this helped me .Thanks for your quick response.


#8

Extra

The only time we do not need break is if the statement is a return.

case "a":
    return "alpha";
case "b":
    // ,,,

#9

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