×

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

Javascript Data Types

An Overview of JavaScript Data Types In computing, there are a number of data types, including numbers, strings, and booleans, to name a few. The role of these data types in...

5 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 Image resize before upload

Image resizing can be a quite tedious task, so it is usually done on the server-side. The resized image file is then delivered to the client side. However, sometimes the...

3 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.

Callback and Callback Hell in JavaScript

The widely used client-side programming language JavaScript is simple, light, and interpretive. JavaScript is used by the majority of client-side web applications. It is also possible to use JavaScript on...

3 minutes read.

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.

Functional Programming in JavaScript

Most developers work with object-oriented programming while developing their applications, but sometimes they need to change their approach to solve some specific tasks. Although mostly we tend to go for...

6 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 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 Date

In JavaScript Date Object is data type build into the JavaScript language. Data object are created with the new Date(). JavaScript Date instance that represents a single moment in time. JavaScript...

2 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 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 Operators

The concept of operators is the basis of nearly all programming languages used in today's computing systems. Operators facilitate the execution of certain functions. For instance, the (+) symbol is...

8 minutes read.

Javascript Password Validation

Here we see that how to validate any password field. Like password field can be blank and length of password is minimum 8 characters. Example <!DOCTYPE html>   <html>   <head>   <script>   functionpass_validation()   {     var password=document.myform.password.value;     if (password==null || password=="")   {     alert("password can't be blank");     return false;     }   else if(password.length<8)   {     alert("Password must be at least 8 characters long.");     return false;       }     }     </script>   </head>   <body>   <form name="myform" method="post" action="register.php" onsubmit="return pass_validation()" >   Password: <input type="password" name="password">   <input type="submit" value="submit">   </form>   </body>   </html> Try Now ← Prev Next → ...

1 minute 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 Math

Math is build-in object that has properties and methods for mathematical constants and functions. It allows you to perform mathematical tasks on numbers. Syntax varpi_val = Math.PI; varsin_val = Math.sin(30); Examples Math.pow() Math.pow(x,y) returns the value of x to the power...

2 minutes read.

Javascript Document Object

Document object represents the whole HTML documents. When HTML document is loaded in browser it becomes the document object. It is the root elements that represent the HTML documents. With the help of...

2 minutes read.

Synchronous and Asynchronous in JavaScript

JavaScript is a powerful and versatile language that is used all over the web, from small websites to large applications. It is essential for developers to understand the differences between...

9 minutes read.

Javascript Variable

Variables are used to store values (name="Ram") or expressions (Sum=x+y). Before using of variable first we need to declare it. We use keyword var to declare a variable like this: var name; There are two types of variables: Local Variable ...

1 minute read.

What is Ternary Operator in JavaScript?

In some cases, a ternary operator can be used instead of an if-else expression. A ternary operator examines a condition and then runs a block of code in response to...

4 minutes read.