What is a switch Statement?

Going by Wikipedia's definition,

A switch statement is a type of selection control mechanism used to allow the value of a variable or expression to change the control flow of program execution via search and map.

To present it in a more simpler view,

A switch Statement is one used to parse different conditions based on predicted cases.

A very practical example of that is exhibited in Street lights 🚦,where cases of go, stop and get ready are parsed based on conditions (colour).

Without much ado, Let's delph into the coding aspect of it.

/* here we want to use switch to choose
people's responsibilities based on thier 
profession.
*/ 
var firstName = 'Alexis'
var job = 'teacher';
// let's now switch the job and assign obligations
switch (job){
       case 'teacher':
       case 'tutor' :.    🔀 updated case
       case 'instructor':
        console.log( firstName + 'teaches Students' )
       break;
       case  'driver':
       console.log(firstName + 'drives an Uber in Lisboa')
       break;
       case 'designer' :
       console.log(firstName + 'design awesome stuffs')
       break;
       default :
       console.log(firstName + 'does something else')
}
//console logs Alexis teaches student
/*updating the job to driver switches it to 
Alexis drives Uber in Lisboa... and it switches
as we update the job variable.
*/

Briefly explaining the switch syntaxes,

After having a variable of what we intend to switch,

We open a switch statement switch which is followed by a curly braces {} where everything else goes in between. Inside the curly braces, we open a case followed by the variable name we want to switch to, followed by a column to separate the expression from the case : and finally ended by a break keyword in order to paulsate the switching if the Case match the variable. Else it continues switching to find a perfect match.

Mind you , a single block can accommodate multiple case.

Check the previous code snippet to see us update the case block with other keywords other than 'teacher' .

Exercise: Use the Switch Statement to build the algorithm for a street light 🚦. Good luck.

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/1616e44e-fc93-4158-bd87-3f4afa85739c/images_(42).jpeg