Switch Case- Its mechanism !

switch.jpg

We all know that we have to take decisions in programming based on various factors like user input , different conditions etc. To take decisions , programming languages provide various decisional statements and expressions such as if-else, switch case statement , ternary expression etc.

Lets talk about the Switch Case and its mechanism.

Switch Case

Switch case is a conditional statement which has different cases inside it. It takes a variable and checks it to each case which we provided.If that variable matches with any case, then the code inside that case will get executed.

After every case we have to use a break statement which stops the execution of the code when desired case is matched.

Example

let number = 3;
switch(number){
   case 1:
      \\Code to be executed
      break;
   case 2:
      \\Code to be executed
      break;
   case 3:
      \\Code to be executed
      break;
   default:
     \\ if no case is matched this default code will get executed
}

Here, Case 3 will get executed.

But there is a catch in the mechanism of switch statement.

When we pass a variable value in switch case (like number=3 in the above example), it took that value and try to match exactly with the value in each case. If the value matched exactly with a case it executes the code of that case and if not it will execute the default case.

Example

let number = 3;
switch(number){
    case number>2:
        alert(`Number is greater than 2`);
        break;
    case number<2:
        alert(`Number is less than 2`);
        break;
    default:
        alert(`Match Not found`);
}

In the above example , switch will take number = 3 and try to match exactly with each case. In the above example, it will not find the exact match because in case number>2 (number is greater than 2 , not exactly equals to 3)therefore it will go to the next case , same thing happen there, so it will go and execute the default case.

Here is the solution of this problem

let number = 3;
switch(true){
    case number<2:
        alert(`Number is less than 2`);
        break;
    case number>2:
        alert(`Number is greater than 2`);
        break;
}

In above example , switch will take true and try to match it with cases, in the first case number < 2 (here it wil replace the number with 3 and try to match ,3<2 ) which returns false , so it will go to the next case.

In the next case number > 2 (here it wil replace the number with 3 and try to match ,3>2 ) which returns true which is equals to the value which switch is trying to match(true) and hence it will execute this case and the code inside it.

This is how switch case works.

Thank you for reading !