×

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

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 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 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 radio button checked value

What are radio buttons? A radio button is defined as an icon that is used to take input from the user. The user can choose only one option(value) from the group...

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

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

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 Forms Validation

Form validation works at server, after client had entered all the necessary details and then pressed submit button. JavaScript provides the facility to validate the form on the client side...

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

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

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

Javascript Find Object In Array

What is find() method? It returns the value of the first element in the given array that fulfils the given testing function. However, if no values from the array are able...

3 minutes read.