Skip to main content

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.

Syntax

switch(condition){
case
break
}

Example:

let animal = 'tiger'

switch(animal)
{
    case 'tiger':
    case 'lion':
    case 'Dog':
        console.log("Permission granted upon Noah's ark")
        break;
    case 'Carrot':
        console.log("Not an animal")
        break;
    case 'chair':
    default:
        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.
Tags
Submitted by arilio666 on October 6, 2021

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.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.