Table of Contents
Back Button
Back to Chapter
Control Statements
No items found.
Function & Events
No items found.
Array and its Types
No items found.
OOP : Object Oriented Programming
No items found.
Javascript Standards
No items found.
HTML DOM
No items found.
Javascript : Advanced 1
No items found.
Javascript : Advanced 2
No items found.
Additional JavaScript
No items found.

Switch

Introduction

Switch Statement is used, when you have multiple definite conditions.

Understanding of Switch Statement

When you use the Switch statement, first it evaluates the expression. It then looks for the first case clause whose expression evaluates the same value as the result of the input expression. then, It executes the associated statements.

If no matching case clause is found, the program looks for the optional default clause, and if found,  executes the associated statements.

Flow Chart

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/4a85c5b4-69ec-48b7-9a61-3dfd87e48d07/hj_(1).jpg

Syntax :

switch(expression) { case value1: // case 1 break; case value2: // case 2 break; case valueN: // case N break; default: // default }

Notes:

  • The default clause is optional, if person has not entered any valid input then the default statement will be executed.

By convention, the default clause is the last clause, but it does not need to be so.

Example

In the following example,

We are trying to Create a Simple Calculator.

var num1=50,num2=20; var operation = prompt("Please Enter Operation "); switch (operation) { case '+': console.log(num1 + num2); break; case '-': console.log(num1 - num2); break; case '*': console.log(num1 * num2); break; case '/': console.log(num1 / num2); break; default: console.log("Sorry!!! No Valid Operation is Provided"); }

Here :

When you Press + then Output will be num1 + num2 i.e. 50+20

When you Press - then Output will be num1 - num2 i.e. 50-20

When you Press * then Output will be num1 * num2 i.e. 50*20

When you Press / then Output will be num1 / num2 i.e. 50/20

Ask queries
Contact Us on Whatsapp
Hi, How Can We Help You?