Skip to content Skip to sidebar Skip to footer

Switch Case Jumps To Wrong Case In Javascript (how To Properly Use The Break Command)

My code is not so long so I am pasting all of it here. The code is not complete but when I run it it first jumps to case 'start' which it is supposed to, and then jumps to case 'en

Solution 1:

The problem is that you are missing the break keyword after your case code. Without the break, subsequent blocks will be executed, that is why end is executed after start code. You can read more about this on this W3Schools link.

Additionally, from the JS reference:

The optional break statement associated with each case label ensures that the program breaks out of switch once the matched statement is executed and continues execution at the statement following switch. If break is omitted, the program continues execution at the next statement in the switch statement.

So your code should look like:

functionstepStream(stream,step){
                switch (stream[step]){
                    case"start":
                        console.log("Started reading stream...");
                        break;
                    case"end":
                        var success = "Finished reading dataStream.";
                        console.log(success);
                        return success;
                    default:
                        throw"Data stream format is bad";                  
                    case"gesture":
                        //commUGesture(stream[i+1]);//createLogLine("robot:CommU","event:gesture:"+stream[i+1]);console.log("Running case gesture! But why?");
                        step+=1;
                        stepStream(stream,step);
                        break;
                    case"say":
                        step+=1;
                        stepStream(stream,step);
                        break;
                    case"sleep":
                        step+=1;
                        stepStream(stream,step);
                        break;
                }

Your "end" case has a return at the end, hence the code doesn't fall through to the other cases. Ideally, there should be a break at the end of each.

Solution 2:

You forgot to add a break statement in the start block, therefore it falls through to the end block.

Solution 3:

Problem is simple all switch case have to end with break or return statements in your case that is missing.

switch(var1)
{
    case"start":
        console.log("Started");
        break;
    case"end":
         console.log("stopped");
         return"";
     .
     .
     .
}

Solution 4:

The code will start running at the first matching "case", but it only stops running when it has reached a "break" or "return" statement;

Post a Comment for "Switch Case Jumps To Wrong Case In Javascript (how To Properly Use The Break Command)"