JavaScript - SPLessons
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

JavaScript Switch

JavaScript Switch

shape Description

JavaScript Switch statement is used to perform different actions based on different conditions. The statement will select a particular code to execute from several blocks of code. Switch statement can be used for decision making and is similar to if…else statement. JavaScript Switch allows variable or expression value to change the control flow of program execution. This is impossible with else-if as the statement is more complex and the developer gets confused. Hence, switch statements would be the best option in such case.

shape Flow Chart

shape Syntax

The JavaScript Switch statement starts with the keyword switch followed by the expression/condition represented in parentheses. Below expression is the syntax for JavaScript Switch statements.
switch(expression) { case value1: //statements; break; case value2: //statements; break; case value3: //statements; break; . . case value n: //statements; break; default : //statements; break; }
In the above syntax, the expression is compared with case 1. If the condition is satisfied, then the corresponding statement gets executed until the break is reached. Otherwise (if it does not satisfy the condition), switch goes to the next case and the process continues. If neither case is satisfied, then switch executes the statements of "default case".

shape Example

[c] <!DOCTYPE html> <html lang="en"> <head> <meta charset=utf-8> <title>JavaScript Switch statement : Example-1</title> <link rel="stylesheet" type="text/css" href="example.css"> </head> <body> <h1>JavaScript : switch statement</h1> <form name="form1" action ="#"> Input Grade type : <input type="text" name="text1" value="A" /> <br /><br /> <input type="button" value="Marks check" onclick='marksgrade()' /> </form> <script src="codejs.js"></script> </body> </html> [/c] Output:

Summary

shape Key Points

  • JavaScript Switch case is helpful when multiple conditions exist in the program.
  • Break keyword stops the execution, if the condition is true.
  • If none of the condition is true, then the default block gets executed.

shape Programming Tips

In switch case statement, fixed integer value conditions can only be checked.