×

Javascript Switch Statement

Introduction

Conditional statements are simple building blocks in programming languages and are utilized fairly frequently. This portion of Developing Conditional Statements in JavaScript talks about how to utilize the if, else, and else if keywords to control the program flow based on alternative conditions, typically initiated by user input. Aside from the if-else construct, JavaScript also has the switch statement. This kind of conditional statement checks an expression against a set of possible cases and executes the corresponding blocks of code for cases that pass the test. The switch statement is similar to using several else if statements and can typically be exchanged interchangeably.

This tutorial will be discussing the switch statement in more detail, as well as its related keywords: case, break, and default. Lastly, we will be discussing how to control multiple cases inside a switch statement.

What is switch statement

A switch statement is a unique type of conditional statement in JavaScript. The program starts executing when the switch condition is satisfied, comparing the input value with one or more of the cases listed in the switch structure. Each case is preceded by a 'break' statement, which determines the flow of execution in the program. One must also provide a 'default' block so that the program will run normally in case the input does not satisfy any of the provided case options in the switch statement.

JavaScript provides a large number of methods of controlling conditions, including the if-else method, if-else-if method, while method, and do-while method, among others. Out of all the various methods, the switch statement provides the ability to execute a special group of instructions when the condition is satisfied.

A switch statement typically has multiple case blocks and an optional default block. Based on the condition, one or more case blocks will be executed if they are satisfied. If none of the case blocks are satisfied, the default block will be executed automatically if it is available in the code.

Syntax of JavaScript Switch Statement

The basic syntax of JavaScript in a switch statement is as follows:

switch(an expression which needs to be checked) {

case x:

// block of code or instructions

break;

case y:

// block of code or instructions

break;

default:

// block of code or instructions for default condition

}

Flow Diagram

Given below is the flowchart of the switch statement:

JavaScript Switch Statement

How does the Switch Statement work in JavaScript?

A switch statement typically includes three main parts:

  1. The expression to be evaluated.
  2. The cases that are equal to the expression to be evaluated.
  3. The default case, which will be executed when none of the cases are satisfied.

Let us now examine the operation of this statement structure.

The expression to evaluate – This section includes testing the expression to be evaluated. The execution of the switch case will be based on which case is equal to the expression to be evaluated.

Different cases – After testing the expression, the case equal to the expression will be executed.

Default case – In situations where none of the switch cases are satisfied, the default case will be executed.

Examples

Some examples are presented below:

Example 1

Suppose an example where a user is prompted to type a number in an input box. If the number typed is less than 10, the program will print the number typed by the user; otherwise, it will print a message saying that the number typed is greater than 10.

To achieve this, simply copy the code below and place it in your HTML file.

Code

<!DOCTYPE html>

<html>

<body>

<h2>Example for JavaScript switch statement</h2>

<label>Enter the number in textbox</label>

<input type="number" id="inputBox"/>

<input type="button" onClick="checkVal()" value="Check value">

<label id="labelVal"></label>

<script>

var text = '', labelVal = "";

function checkVal(){

text = document.getElementById("inputBox").value;

labelVal = '';

text = Number(text)

switch(text) {

case 1:

labelVal = "You entered 1";

break;

case 2:

labelVal = "You entered 2";

break;

case 3:

labelVal = "You entered 3";

break;

case 4:

labelVal = "You entered 4";

break;

case 5:

labelVal = "You entered 5";

break;

case 6:

labelVal = "You entered 6";

break;

case 7:

labelVal = "You entered 7";

break;

case 8:

labelVal = "You entered 8";

break;

case 9:

labelVal = "You entered 9";

break;

default:

labelVal = "Enter value less than 10";

}

document.getElementById("labelVal").innerText = labelVal;

}

</script>

</body>

</html>

Output

JavaScript Switch Statement
JavaScript Switch Statement

Example 2

We will now describe the process of executing multiple switch statements in JavaScript.

Executing Multiple Cases When Conditions Are Met.

At this stage, we will describe how to execute multiple cases. Please copy the code given below and place it in an HTML file for running.

Code

<!DOCTYPE html>

<html>

<body>

<h2>Example for JavaScript switch statement</h2>

<label>Enter the number in textbox</label>

<input type="number" id="inputBox"/>

<input type="button" onClick="checkVal()" value="Check value">

<label id="labelVal"></label>

<script>

var text = '', labelVal = "";

function checkVal(){

text = document.getElementById("inputBox").value;

labelVal = '';

text = Number(text)

switch(text) {

case 1:

labelVal = labelVal + " You entered 1";

case 2:

labelVal = labelVal + " You entered 2";

case 3:

labelVal = labelVal+ " You entered 3";

break;

case 4:

labelVal = labelVal+ " You entered 4";

case 5:

labelVal = labelVal+ " You entered 5";

case 6:

labelVal = labelVal+ " You entered 6";

break;

default:

labelVal = "Enter value less than 10";

}

document.getElementById("labelVal").innerText = labelVal;

}

</script>

</body>

</html>

Output

JavaScript Switch Statement

Conclusion

JavaScript is a programming language with many concepts that need to be studied in detail. Among them is the switch statement. This kind of conditional statement runs code to check whether the expression satisfies the given condition based on its evaluation, returning a value in the end. Conditional statements are widely used for a variety of logical programming expressions in different programming languages.


Related Topics

Array to String in JavaScript

As a web developer, you often have to deal with multiple data types in a single application. How to convert an array to a string in JavaScript is essential for...

19 minutes read.

Javascript Cookies

Cookie is a piece of data which is sent from a website and stored locally by the user's browser. Cookie is needed because HTTP is stateless protocol. Today most of...

1 minute read.

Javascript comment

Introduction In programming languages, comments are a method to include meaningful annotations within the code that the compiler or interpreter will ignore at run time. That is to say, though comments...

7 minutes read.

JavaScript Function

An important part of JavaScript is the ability to create new functions within <script>.....</script> tag. To declare a function in JavaScript using function keyword. We call JavaScript function multiple times to reuse the...

3 minutes read.

D3.js Tutorial

Introduction of D3.js D3.js is referred to as a JavaScript library that is used to manipulate the documents according to the data. The intensity of D3 is based on web standards...

5 minutes read.

Javascript Page Redirect

The window.location object can be used to get the current page address (URL) and to redirect browser to new page. In some websites when we visit, we face a situation where we...

3 minutes read.

JavaScript setTimeout()

The setTimeout() method creates a timer that, when it expires, runs a function or provides a piece of code. setTimeout() is an asynchronous function, which means that it will not interrupt...

3 minutes read.

Javascript String

String object works with series of characters. It is used to store and manipulate text. There are two ways to create string in JavaScript: String literal. Using new keyword. String literal By using double quotes...

4 minutes read.

Javascript Example

What is JavaScript? JavaScript is a highly versatile programming language. It provides the capability to add interactivity to static web pages, which are designed with HTML and CSS. It also provides...

5 minutes read.

JavaScript p5.js

Introduction to p5.js P5.js is a JavaScript library for creative programming. It is built on Processing, a coding environment for creativity. Processing's major goal is to make it as simple as...

4 minutes read.

Design a BMI calculator using JavaScript

BMI calculator BMI stands for Body Mass Indicator. It is a numeric value which is calculated based on the height and weight of a person. It represents the fatness of the...

4 minutes read.

Javascript Event

Events are things that happen, usually user action, that are associated with an object. All object have properties and methods. Some objects also have events. The event handler is a command that is...

1 minute read.

JavaScript dropdown onchange

What is onchange event? It is an event in JavaScript used to make the web pages dynamic. The onchange event gets triggered whenever the value of an event changes. It usually...

3 minutes read.

JavaScript Arrays

JavaScript Arrays: JavaScript Arrays are a type of variables that allows us to store the individual or the group of values under a single variable. What is an Array in JavaScript? The array...

6 minutes read.

Javascript Object

An object is an entity having state and behavior. JavaScript is an object oriented scripting language. JavaScript is template based not class based but we can create object directly. Syntax to...

2 minutes read.

Javascript Print

JavaScript help's the functionality using the print function of window object. In JavaScript print function window.print() print the current web page when it executed. We can call function directly using onclick...

1 minute read.

Javascript Re-Password Validation

Example <!DOCTYPE html>   <html>   <head>   <script>   function pass_validation()   {   var firstpassword=document.f1.password1.value;     var secondpassword=document.f1.password2.value;     if(firstpassword==secondpassword){     return true;     }     else{   alert("Password does Not Match");     return false;     }     }    </script>   </head>   <body>   <form name="f1" action="/JavaScript/Index" onsubmit="return pass_validation()">   Password:<input type="password" name="password1" /><br/>   Re-enter :<input type="password" name="password2"/><br/>   <input type="submit">   </form>   </body>   </html> Try Now ← Prev Next → ...

1 minute read.

JavaScript Console log Multiple variables

What does console.log() do in JavaScript? The console.log() is a function in JavaScript language. It is used to: Print any message in the console which is visible to the userPrint the values...

3 minutes read.

Javascript Switch Statement

Introduction Conditional statements are simple building blocks in programming languages and are utilized fairly frequently. This portion of Developing Conditional Statements in JavaScript talks about how to utilize the if, else,...

5 minutes read.

JavaScript setInterval()

On the Window and Worker interfaces, the setInterval() method calls a function or executes a snippet with a specified time delay between each call. This function provides an interval ID that...

4 minutes read.