Switch Statement in JavaScript


The "switch" statement provides a way to execute different blocks of code based on the value of an expression. It offers an alternative to multiple nested "if-else" statements when you have several possible conditions to check.

Syntax:
    switch (expression) {
        case value1:
            // Code to be executed if the expression is equal to value1
            break;
        case value2:
            // Code to be executed if the expression is equal to value2
            break;
            // More cases can be added here
        default:
            // Code to be executed if the expression does not match any of the cases
            break;
    }


Source Code

HTML Code
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Tutor Joes</title>
</head>
<body>
 
	<script src="js/script.js"></script>
</body>
</html>
To download raw file Click Here

script.js
/*
switch(choice)
{
  case choice:
    -----
    break;
  case choice:
    -----
    break;
  default:
    ----
    break;
}
*/

let num=5;

switch(num)
{
  case 1:
    console.log("One");
    break;
  case 2:
    console.log("Two");
    break;
  case 3:
    console.log("Three");
    break;
  default:
    console.log("Invalid Input");
    break;
}
To download raw file Click Here

List of Programs


JS Practical Questions & Answers


JS Practical Project