JavaScript - SPLessons

JavaScript Switch

Chapter 11

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.
case value1:

case value2:

case value3:
case value n:

default :

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

<!DOCTYPE html>  
<html lang="en">  
			<meta charset=utf-8>  
			<title>JavaScript Switch statement : Example-1</title>  
			<link rel="stylesheet" type="text/css" href="example.css">  
			<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()' />  
			<script src="codejs.js"></script>  



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

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