JavaScript Switch Case statement

Updated on 01 Mar 2012,
Published on 10 Mar 2008

To execute a single block of code satisfying a condition in case statement of JavaScript switch-case statement is used. Break keyword is used in every case statement to exit the switch statement so that it could not enter into other case statement.

JavaScript Basics Examples:

You can see the live samples and examples of JavaScript Basics from the following links:

Syntax of JavaScript Switch case statement

switch ([variable])
{
    case 1:
    code block 1 to be executed here;
    break;

    case 2:
    code block 2 to be executed here;
    break;

    default:
    code block to be executed if case 1 and case 2 don’t return true for any condition of variable passed is switch statement;
}

No break is required in default case of JavaScript statement it automatically exits after default case. 

Example of JavaScript Switch case Statement

    var n;
    n = (Math.random() * 10);
    n = Math.ceil(n);

    switch(n)
    {
        case 5:
            document.write('Random Number is 5');
            break;
 
        case 6:
            document.write('Random Number is 6');
            break;
 
        case 7:
            document.write('Random Number is 7');
            break;
 
        case 8:
            document.write('Random Number is 8');
            break;
 
        case 9:
            document.write('Random Number is 9');
            break;

        case 10:
            document.write('Random Number is 10');
            break;

        default:
            document.write('Random Number is less than 5');
    }

Above example is a code for a simple JavaScript game to trace the random number greater than 5 using JavaScript switch-case statements.

Output:

You can see the output of above discussed codes from the following link:

JavaScript Switch Case

Continue to next tutorial: For Loops in Javascript to learn how to execute the single javascript code multiple times using iterations.

0 Responses to "JavaScript Switch Case statement"
Leave a Comment
* required
* required
* will not be published
* optional
* hint: http://www.example.com
  • Subscribe via Email
  • HIRE EzineASP.Net Developers