JavaScript: Switch Case

A switch statement is a fundamental control structure used to perform basic actions based upon different conditions passed within. In a switch case, we pass upon a condition that checks whether the state gets satisfied upon the switch block of its presence.




let animal = 'tiger'

    case 'tiger':
    case 'lion':
    case 'Dog':
        console.log("Permission granted upon Noah's ark")
    case 'Carrot':
        console.log("Not an animal")
    case 'chair':
        console.log("Not permitted inside the ark")    

Output: Permission granted upon Noah's ark

  • In this code, we have declared a variable named animal with value tiger.
  • We simply tell the switch case to search for the value tiger assigned and execute that case body and break.
  • This is the basic doing of a switch case. It searches among the body of the case for the tiger, and when it matches, it executes the case body and breaks out of the loop.
  • If we don't use a break, the loop continues to proceed to the end.
  • Now a default at the end of the code we mentioned is nothing but like an else, which is satisfied when the switch case doesn't match any of the provided variables.
Wed, 10/06/2021 - 09:09

Authored by

Ashwin is working with iVagus as a Technical Lead. He has experience in various technologies like Cypress, JavaScript, TypeScript, Rest Assured, Selenium, Cucumber, and Java.