Switch Case in JavaScript ! with a small example

Hello everyone. In this tutorial, we will be learning what is  switch case in java script ,To understand in better way  we are going to take a small example

Decision making are needed when, the program encounters the situation to choose a particular
statement among many statements. If a programmer has to choose one block of statement among many.
Alternatives, nested if…else can be used but, this makes programming logic complex.

With a small example! How do we use switch case in java script.

    
// Here using switch case to know the  name of prime minister by position

const position = 13
  // check who is the 13th prime minister of india
switch(position){
    case  1:          //It will compare the value of position and case 1
    console.log("Jawaharlal Nehru")
    break;
    case 2:
    console.log("Lal Bahadur Shastri")
    break;
    case 3 :
        console.log("Indira Gandhi")
     break;
     case 4:
      console.log("Morarji Desai")
      break;
      case 5:
      console.log("Charan Singh")
      break;
      case 6 :
      console.log("Rajiv Gandhi")
       break;
       case 7:
        console.log("Vishwanath Pratap Singh")
        break;
        case 8 :
        console.log("Chandra Shekhar")
        break;
        case 9:
        console.log("P.V Narasimha Rao")
         break;
        case 10 :
        console.log("Atal Bihari Vajpayee")
         break;
         case 11:
        console.log("HD Deve Gowda")
        break;
        case 12 :
        console.log("Inder Kumar Gujral")
       break;
       case 13:
        console.log("Manmohan Singh")
        break;
        case 14 :
        console.log("Narendra Modi")
        break;
            default:
                console.log("you entered wrong input")
}


Output :

Manmohan Singh

Switch statement provides a way to execute different code of blocks based on different condition

  • The expression inside the switch statement is evaluated once .
  • The value of position is compared with each case label using (strict equality ===)
  • If the matching is is found 13 the corresponding code block “Manmohan Singh” is executed
  • Then the break statement immediately stops further checking of other cases
  • If suppose none of the case value matches the code block in the default block executed

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top