How to use Javascript switch case Example

Javascript switch case Example

In this tutorial , you will learn how to use javascript switch case and Let's learn about the switch statement, which is an alternative way of writing a complicated if/else statement, when all we want to do is compare one value to multiple different options, basically. So in this example, let's say we have a weekday variable and a different activity. so, here I am going to create an activity for each day and basically how this code would work in the real world.

Read also:

Javascript to change the background colour font checkbox

How to create a accordion ui design examples in html

8 Best Free Keyword Research Tools for SEO

what is domain and web hosting

Usually, most of the data are coming from the user's input and select an option to do that's used by users in a browser. Now the javascript switch case gonna compare to multiple options. If we use an if/else statement with multiple "else" on if blocks, we can easier to use a switch statement.

The switch case will be evaluated once and compared with the values of each case and then if the switch case matches and the associated block of code are executed and then break the condition and switch statement. If the switch case does not match and the direct move to the default code block is executed.

 


Syntax:



switch()
{
case 'name':
 break;
............
............
default:
break;
}


Switch case in Javascript Example:





const day="sunday";
switch(day)
{
case 'monday':
    console.log('Read Science');
break;
case 'tuesday':
    console.log('Read Social');
break;
case 'wednesday':
    console.log('Read Maths');
break;
case 'thursday':
    console.log('Read English');
break;
case 'friday':
     console.log('Read Computer science');
break;
case 'saturday':
     console.log('Ready for the Mock Test');  
break;
case 'sunday':
     console.log('Take Rest');
break;
default:
 console.log('not valid day');
 break;
}

Output:



Sunday:

Take Rest


how all this different stuff works. So let's say on Monday I plan my study structure and here we can actually execute multiple lines of code and we don't need curly braces for that. So after the case and the colon, all the lines were executed very well.

 


Javascript switch case Example:



<p id="output"> </p>


const weekday = ["sunday","monday","tuesday","wednesday","thursday","friday","saturday"];
const d = new Date();
let day = weekday[d.getDay()];
switch (day) 
{
case 'monday':
      text = 'Read Science';
break;
case 'tuesday':
      text = 'Read Social';
break;
case 'wednesday':
     text = 'Read Maths';
break;
case 'thursday':
    text = 'Read English';
break;
case 'friday':
     text = 'Read Computer science';
break;
case 'saturday':
     text = 'Ready for the Mock Test';  
break;
case 'sunday':
     text = 'Take Rest';
break;
default:
    text = 'not valid day';
 break;
}
document.getElementById("output").innerHTML = text;

Take Rest

Previous Post Next Post