×

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

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

Minify JavaScript

What do you mean by the term ‘Minification’? The technique of minification reduces the amount of code and markup in your websites and scripting files. It's one of the most used...

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

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.

Javascript Number

The Number object is a wrapper object which allows you to work with numerical values. The number object is created using the Number() constructor.It may be integer or floating-point. Syntax var n=new Number(value); Examples <!DOCTYPE html>   <html>   <body>   <script>   var x=100;//integer value   var y=100.7;//floating point value   var z=12e5;//exponent value, output: 1200000   var n=new Number(20);//integer value by number object     document.write(x+" "+y+" "+z+" "+n);   </script>   </body>   </html> Try Now Output 100 100.7 1200000 20 Description The primary...

1 minute read.

Javascript Window Object

The window object represents a window in browser. An object of window is created automatically by the browser. Window is the object of browser, it is not the object of JavaScript. The...

3 minutes 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 redirect URL with parameters

Data can be often passed between web pages as information in URL parameters or query strings. A URL (Uniform Resource Locator) can have a single parameter or multiple parameters.Parameters can...

4 minutes read.

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 Redirect Button

What is a redirect button? When a button acts as a hyperlink, it is known as a redirect button. On clicking the button, it transfers the user to another page. How to...

3 minutes read.

JavaScript moment date difference

Often date differences are required on the web platforms for various reasons. They can be: To find the duration, of course, someone is pursuingTo find the age of a user from...

7 minutes read.

Javascript getElementByID

The document.getElementById() method returns the element of specified id. In below example we receive input field by using document.getElementById() method, here document.getElementById() receive input value on the basis of input field...

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 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 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 input maxlength

Various attributes often accompany the input tag in HTML to change the properties of the input field. Maxlength() is one such attribute. The maxLength attribute defines the maximum number of characters...

2 minutes read.