Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch-case typescript case not working on string [duplicate]

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.

like image 509
samisaviv Avatar asked Jan 30 '20 13:01

samisaviv


People also ask

Can we use string in switch-case in typescript?

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.

Do switch cases work with Strings?

Yes, we can use a switch statement with Strings in Java.

Can switch-case Take 2 values?

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.

Does typescript switch need break?

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.


1 Answers

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");
}
like image 181
Ankit Agarwal Avatar answered Sep 28 '22 01:09

Ankit Agarwal