CodingBison

A program may need to execute different sets of statements depending upon a condition. For example, a program can execute a specific set of statements to invoke a particular action, when a user provides a specific input. Thus, running these statements is conditional upon a specific user input. Alternatively, if the user does not provide the specified input, then the program can simply skip running these statements.

JavaScript provides several conditional constructs for executing tasks that rely upon the value of a condition (a variable or an expression). It supports four types of conditional constructs: (a) if, (b) if-else, (c) if-"else if"-else, and (d) switch. We can consider the first two forms as simplification of the if-"else if"-else form.

We begin by providing (below) generic formats of the first three constructs. For the "else if" clause, we show two conditions ("condition1" and "condition2") with the "else if" clause; however, a program can have as many number of such clauses as it requires.

 // Format of a single if expression 
 if (condition) {
     Execute some statements
 } 

 // Format of an if-else expression 
 if (condition) {
     Execute statements pertaining to the "condition"
 } else {
     Execute Alternative statements
 }

 // Format of an if-"else if"-else expression 
 if (condition0) {
     Execute statements pertaining to the "condition0"
 else if (condition1) {
     Execute statements pertaining to the "condition1"
 else if (condition2) {
     Execute statements pertaining to the "condition2"
 } else {
     Execute Alternative statements
 }

Next, let us write a simple program that implements these conditional expressions. The program (provided below) uses these expressions to find specific magical creatures from an array of magic creatures. As we can see, we provide print statements only when the specified condition becomes true.

 <!doctype html>
 <html>
 <div id="idDiv"> </div>

 <script type="text/javascript"> 
 // Get a handle of the div element.
 var elem = document.getElementById("idDiv");

 // Define aMagic with some initial values.
 var aMagic = ["Wise Dragon","Mischievous Goblin","Dark Lord","Strong Griffin"];

 // An if clause: find someone who can spit fire. 
 var i = 0;
 for (i=0; i < aMagic.length; i++) {
     if (aMagic[i] == "Wise Dragon") {
         elem.innerHTML += "[if] Found " + aMagic[i] + "<br><br>";
         break;
     } 
 }

 // An if-else clause: find someone with an appetite for mischief. 
 for (i=0; i < aMagic.length; i++) {
     if (aMagic[i] == "Mischievous Goblin") {
         elem.innerHTML += "[if-else] Found " + aMagic[i] + "<br><br>";
         break;
     } else {
         elem.innerHTML += "[if-else] Searching... <br>";
     } 
 }

 // An if-"else if"-else clause: find all those who can fly. 
 for (i=0; i < aMagic.length; i++) {
     if (aMagic[i] == "Wise Dragon") {
         elem.innerHTML += "[if-\"else if\"-else] Found " + aMagic[i] + "<br>";
     } else if (aMagic[i] == "Strong Griffin") {
         elem.innerHTML += "[if-\"else if\"-else] Found " + aMagic[i] + "<br>";
     } else {
         elem.innerHTML += "[if-\"else if\"-else] Searching... <br>";
     } 
 }
 </script>
 </html>

And, here is the output of the above program; to run the above program (save in a file, let us say, "conditional.html", and point the browser to that file). Both, if and if-else expressions use a "break" to exit the loop when the condition becomes true. Since the if-"else if"-else clause has multiple conditions, we do not provide a "break" and let the loop run for all array elements.



Figure: Using conditional expressions.

JavaScript also provides a handy form of the if-else conditional expression in a ternary form: "if (condition) ? doThis1 : doThis2". This means that if the "condition" is true, then we execute "doThis1", else, we execute "doThis2". A simple example could be to find the maximum of the two numbers; we provide the example below. The output for this example is "The maximum of these two numbers is 1000".

 <!doctype html>
 <html>
 <script type="text/javascript">

 var varNum1 = 500;
 var varNum2 = 1000;

 varMax = (varNum1 > varNum2 ? varNum1 : varNum2);
 document.write("The maximum of these two numbers is " + varMax);

 </script>
 </html>

switch Statement

For certain cases of if-"else if"-if conditional expression, JavaScript provides a more compact version called a switch. If an if-"else if"-else clause has conditions that belong to a set of values, then we can also use the switch expression. This variant allows a program to check if the value of a passed expression (or value) belongs to a set of values.

Here is a pseudo-code of a switch statement; the values (value0, value1, ...) do not necessarily have to be integer constants and can be variables or expressions.

 // A switch expression 
 switch (expression) {
     case value0:
     Execute statements pertaining to the "value0"
     break;

     case value1:
     Execute statements pertaining to the "value1"
     break;

     default:
     Execute Alternative statements
     break;
 } 

A switch works by comparing the passed value (or expression) to different values (or cases) from a set (value0, value1, ...). The switch starts by comparing the passed value with the first value from the set. If the comparison succeeds, then it executes statements pertaining to the first value and breaks; otherwise, it falls to the next value. This way, it continues to compare the passed value with each value from the set until it finds a match. Worst case, if the passed value does not match any of the switch values, then it goes to the "default" case and from there, it exits the switch. Note that we must provide a break statement at the end of a given case, if we want the switch to return after it is done processing that case.

To demonstrate a switch statement, let us rewrite the earlier if-"else if"-else example. The three switch cases check a passed name with names of three different magical beings; if the passed name matches with any names from the set, then it prints their properties. Also, since two of these magic beings (Dragons and Griffins) share a common ability of flying, we provide another switch statement, where we intentionally remove the "break" keyword to make the switch fall-through to handle these two magical "flying" creatures.

 <!doctype html>
 <html>
 <div id="div_id"></div>

 <script type="text/javascript"> 
 // Get a handle of the div element.
 var elem = document.getElementById("div_id");

 // Define aMagic with some initial values. 
 var aMagic = ["Magical Elves", "Wise Dragon", "Strong Griffin"];

 // A switch statement. 
 var i = 0;
 for (i=0; i < aMagic.length; i++) {
     switch (aMagic[i]) {
     case "Magical Elves": 
         elem.innerHTML += "[switch] someone of divine origins: " + aMagic[i] + "<br>";
         break;
     case "Wise Dragon": 
         elem.innerHTML += "[switch] someone who can fly: " + aMagic[i] + "<br>";
         break;
     case "Strong Griffin": 
         elem.innerHTML += "[switch] someone who can fly: " + aMagic[i] + "<br>";
         break;
     default:
         elem.innerHTML += "[switch] This record seems unknown<br>";
         break;
     }
 }

 // A switch statement with fall-through.
 elem.innerHTML += "<br> Using a Switch statement with Fall-through <br>";
 for (i=0; i < aMagic.length; i++) {
     switch (aMagic[i]) {
     case "Magical Elves": 
         elem.innerHTML += "[switch] someone of divine origins: " + aMagic[i] + "<br>";
         break;
     case "Wise Dragon": 
         // Fall-through 
     case "Strong Griffin": 
         elem.innerHTML += "[switch] someone who can fly: " + aMagic[i] + "<br>";
         break;
     default: 
         elem.innerHTML += "[switch] This record seems unknown<br>";
         break;
     }
 }
 </script>
 </html>

Here is the output from the browser. As expected, the output is same for both the switch statements.



Figure: Using Switch

It is a good practice to provide the comment "// Fall-through". This way, a new programmer assigned to enhance/maintain this code would know that the fall-through has been kept intentionally. Otherwise, if the programmer puts a break statement in place of fall-through (thinking that it is missing!), then he would end up breaking (pun intended!) the application logic.





comments powered by Disqus