Friday, 24 August 2018

JavaScript: Decision making using switch statement

The body of a switch statement is known as a switch block. A statement in the switch block can be labelled with one or more case or default labels. The switch statement evaluates its expression, then executes all statements that follow the matching case label.

Syntax
switch(expression){
         case expression1:
                           //statements
                           break;
         case expression2:
                           //statements
                           break;
         default:
                  //statements
}

switch.html
<!DOCTYPE html>

<html>

<head>
    <title>switch statement</title>
</head>

<body>
    <script type="text/javascript">
        var day = parseInt(prompt("Enter an integer between 1 and 7", 6));

        switch (day) {
            case 1:
                document.write("Sunday");
                break;
            case 2:
                document.write("Monday");
                break;
            case 3:
                document.write("Tueday");
                break;
            case 4:
                document.write("Wednesday");
                break;
            case 5:
                document.write("ThursDay");
                break;
            case 6:
                document.write("Friday");
                break;
            case 7:
                document.write("Saturday");
                break;
            default:
                document.write("You entered wrong day number");
        }
    </script>
</body>

</html>

Load above html page in a browser, it prompts for input.
If you enter 1, it prints Sunday
If you enter 2, it prints Monday
If you enter 3, it prints Tueday
If you enter 4, it prints Wednesday
If you enter 5, it prints ThursDay
If you enter 6, it prints Friday
If you enter 7, it prints Saturday

for all other inputs, it print "You entered wrong day number".




Previous                                                 Next                                                 Home

No comments:

Post a Comment