Switch Statements in JavaScript

Switch statements are similar to ‘If’ statements but they are neater when working with many conditions. This video tutorial explains how to use switch statements. View it below or click here to view it on YouTube.

A switch statement is like an IF statement but is neater when working with many conditions.

Make sure you use the break statement at the end of each case so that the code runs efficiently. If you don’t use the break statement, the program will keep checking through all conditions even if a match has already been found. If none of the conditions are met, then the default case will run.

Take a look at the source code below and try using it in your own program.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Switch Statements</title>
 <script type="text/javascript">
 
 // A switch statement is like an IF statement but is neater when working with many conditions.
 // Use the break statement at the end of each case so that the code runs efficiently.
 // If you don't use break, the program which keep checking through all conditions even if a match has
 // already been found. If none of the conditions are met, then the 'default' case will run.
 
 var city="Sydney";
 
 switch(city){
 case "Melbourne":
 document.write("You are from Melbourne");
 break;
 case "Sydney":
 document.write("You are from Sydney");
 break;
 case "Perth":
 document.write("You are from Perth");
 break;
 case "Brisbane":
 document.write("You are from Brisbane");
 break;
 default:
 document.write("You don't live in a city I recognise.");
 }
 
 
 </script>
 
</head>
<body>
 
</body>
</html>

Next tutorial: While loops

Leave a Reply