Why is Break needed when using Switch?

From MDN

If a match is found, the program executes the associated statements. If multiple cases match the provided value, the first case that matches is selected, even if the cases are not equal to each other.

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 the basic history about Switch is it originated from C and is an abstraction of branch table and a branch table also has an implicit fall-through and requires an additional jump instruction to avoid it.
Also all other languages inherited switch as default C switch semantics mostly choosing to keep the C semantics per default.
So in your switch if break is omitted from all cases, if the match is found program continues execution for next statement. It doesn’t exit from switch after the match is found instead it evaluates all other case below the matched case, as parser thinks cases are combined, since there is no break in between them.
I have modified your code a bit for clear explanation of this behavior.In case A break is omitted.

var dna = "ATTGC";
var outArr = [];
dna.split("").forEach(function(e,i){
switch(e) {
    case "G": outArr[i] = "C"; break;
    case "T": outArr[i] = "A"; break;
    case "A": outArr[i] = "T";
    case "C": outArr[i] = "G"; break;
}
console.log(outArr);
})

So your Output will be like

["G"]
["G", "A"]
["G", "A", "A"]
["G", "A", "A", "C"]
["G", "A", "A", "C", "G"]

In first iteration match will be for case A.

outArr={'T'}

Again Since there is no break statement, it will consider Case C as same block and continues execution there. Now

outArr={'G'}

Similalrly in second iteration it matches for case T but there is a break statement so controls jumps out of the switch and outarr will now be

outArr={'G','A'}

Similarly for other iterations you will get the whole output as posted above.

Updated Bin here

Leave a Comment