5. JavaScript: Switch Statement

Switch statement is more convenient and good alternative of if statement. If you have different conditions, you can use multiple if statements. This practice makes the code lengthy and hard to manage. Developer always try to make the code clean and manageable. Switch statement is a very good alternative.

First look at the syntax:

switch(variable_name){
	case value:
		your code here
	break;
}


Switch
statement takes a variable and compares with available cases which you have mentioned in the block.

switch(variable_name){
	case value1:
		your code here
	break;

	case value2:
		your code here
	break;

        default :
	        Your code
        break;
}

You can also add default block as well.  Default block will execute when all cases will be failed.

Break is a very important keyword in Switch. Every case must have break. Once your provided value is matched with case, execution will break from that point, rest of the code block will be ignored and control will come out from switch statement. But if you will forget to add break statement, javaScript will keep executing all lines of code wethere your required case is executed successfully or not. So Do Not Forget to Add Break with each Case.

Copy the following code in your HTML file and execute in browser.

<script type="text/javascript">
		
var name = "Khan";

switch(name){
   
case "Khan":
     alert("hello user " + name);
     document.write("hello " + name );
break;

case "Bob" :
     alert("hello user " + name);
     document.write("hello " + name );		
break;

default :
     alert("hello unknown user " + name);
     document.write("hello unknown user " + name );
break;
}

</script>

 

Download file from GITHub