This Season
 

How to Create a Switch Statement in JavaScript

JavaScript's switchstatement allows you to specify different actions to be taken based on different values of a variable or expression. Whereas the if statement allows only two alternatives, for the case where an expression is either true or false, switch allows multiple alternatives.

Related Searches:
    Difficulty:
    Moderate

    Instructions

    Things You'll Need

    • JavaScript or text editor
    1. Create a Switch Statement in JavaScript

      • 1

        Enter the skeleton for the switch statement using the following syntax. The expression can be a single variable or a formula.
        switch (expression) { }

      • 2

        Place one or more case statements inside the curly brackets following the switch statement The value given following the word case will often be a constant, such as 1 or "red", but could be any variable or expression. The statements will be executed if the value of the expression given in the switch statement matches the value following the case statement.
        case value: statement(s);

      • 3

        Insert a break statement following the statement or statements in the case command. If you don't, the statements for the next case will be executed, which is probably not what you want.

      • 4

        Place an optional default statement after all the cases. The statements in the default statement will be executed if the value of the expression given in the switch statement does not match any of the values following the case statements above. If you omit the default statement, and the expression given in the switch statement does not match any of the values following the case statements, then nothing will be done.

    Related Searches

    Read Next:

    Comments

    You May Also Like

    Follow eHow

    Related Ads