I have the following switch simple case:
let ca: string = "2";
switch (ca) {
case "2":
console.log("2");
case "1":
console.log("1");
default:
console.log("default");
}
I'm trying to understand why the output of this code is:
2
1
default
My expected output is
2
default
why its print
1
even if ca isn't equal "1"?
EDIT: I know that I can add break
statment - I just trying to understand why case "1"
occurred if ca="2"
Thanks.
Switch case with String In this example, we have a string variable grade. The switch statement evaluates grade variable value and match with case clauses and then execute its associated statements.
Yes, we can use a switch statement with Strings in Java.
Note: Sometimes when default is not placed at the end of switch case program, we should use break statement with the default case. 2) Duplicate case values are not allowed.
The switch statement can include constant or variable expression which can return a value of any data type. There can be any number of case statements within a switch. The case can include a constant or an expression. We must use break keyword at the end of each case block to stop the execution of the case block.
You need to add a break
statement in each of the case
you have for the switch block otherwise it will keep executing further once the match is found.
let ca: string = "2";
switch (ca) {
case "2":
console.log("2");
break;
case "1":
console.log("1");
break;
default:
console.log("default");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With