JavaScript Switch Statement
×

JavaScript Switch Statement

3749

What things compel Developers to use Switch statements in JavaScript?

Although we have discussed about all decision statements used in JavaScript including if, ifelse in our previous topics. Those concepts are used in simple programs, now we are going to discuss how to overcome the complexity of conditional statements in JavaScript.

What outstanding features of switch statements that beat if else statement? As each of them has its own significance. In this Article, we will discuss about every concept included in JavaScript Switch Statement.

When Developers need switch statements while programming?

When they are developing a project in which there is a need to select one option from multiple ones depending upon some variable value. They prefer Switch which is also known as a compound statement.

Why Switch?

a) They can execute multiple statements

b) More convenient

c) Multi-way branch system

d) Use multiple cases


Real-time example illustrating use of Switch

Suppose there a situation occurs when there is a need to test a variable for fifty different values and to perform a specific task depending upon that test. In such case it is less efficient to use if-else statement because code appears more messy Thus, developer prefer switch case.

Flow Chart of a Switch Statement:


Syntax:

switch(exp) {
 case p:
  // statements block
   break;
 case q:
  // statements block
   break;
 default:
  // statements block
}
Let's understand concept through a small example illustrating switch Implementation in JavaScript.

<script type = "text/javascript">
  var q = 7;
  switch (q)
  {
   case 0:
    document.write("q is inefficent person.");
    break;
   case 1:
    document.write("q is average person ");
    break;
   case 2:
    document.write("q is an efficent person");
    break;
   default:
    document.write("q is an extraordinary person");
  }
</script>


Output:
q is an extraordinary person



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments