Conditional Statements
Conditional statements, as the name implies, are used to detect particular conditions arising in the values of the variables you are using in your script. JavaScript supports various such conditional statements, as outlined in the following sections.
The if() Statement
In the previous section we discussed Boolean variables, which we saw could take one of only two values—true or false.
JavaScript has several ways to test such values, the simplest of which is the if statement. It has the following general form:
if(this condition is true) then do this;
Let’s look at a trivial example:
var message = ""; var bool = true; if(bool) message = "The test condition evaluated to TRUE";
First we declare a variable message, and assign an empty string to it as a value. We then declare a new variable, bool, which we set to the Boolean value of true. The third statement tests the value of the variable bool to see whether it is true; if so (as in this case) the value of the variable message is set to a new string. Had we assigned a value of false to bool in the second line, the test condition would not have been fulfilled, and the instruction to assign a new value to message would have been ignored, leaving the variable message containing the empty string.
Remember, we said that the general form of an if statement is
if(this condition is true) then do this.
In the case of a Boolean value, as in this example, we have replaced the condition with the variable itself; since its value can only be true or false, the contents of the parentheses passed back to if accordingly evaluate to true or false. We can test for the Boolean value false by using the negation character (!):
if(!bool) message = "The value of bool is FALSE";
Clearly, for !bool to evaluate to true, bool must be of value false.
Comparison Operators
The if() statement is not limited to testing the value of a Boolean variable; instead, we can enter a condition in the form of an expression into the parentheses of our if statement, and JavaScript evaluates the expression to determine whether it is true or false:
var message = ""; var temperature = 60; if(temperature < 64) message = "Turn on the heating!";
The less-than operator (<) is one of a range of comparison operators available in JavaScript.
try yourself...Extending Our Spam Detector
<!DOCTYPE html> <html> <head> <title>Spam Detector</title> </head> <body> <script> function detectSpam(input) { input = input.toLowerCase(); if(input.indexOf("fake") < 0) { return false; } return true; } var mystring = prompt("Enter a string"); alert(detectSpam(mystring)); </script> </body> </html>
More about if()
The previous examples carry out only a single statement when the test condition is met. What if we want to do more than this; for instance, carry out several statements?
To achieve this, we simply enclose in curly braces ({}) all of the code statements that we want to execute if the condition is fulfilled:
if(temperature < 64) { message = "Turn on the heating!"; heatingStatus = "on"; // ... more statements can be added here }
We can also add a clause to our if statement that contains code we want to execute if the condition is not fulfilled. To achieve this we use the else construct:
if(temperature < 64) { message = "Turn on the heating!"; heatingStatus = "on"; // ... more statements can be added here } else { message = "Temperature is high enough"; heatingStatus = "off"; // ... more statements can be added here too }
Testing Multiple Conditions
You can use “nested” combinations of if and else to test multiple conditions before deciding how to act. Let’s return to our heating system example, and have it switch on the cooling fan if the temperature is too high:
if(temperature < 64) { message = "Turn on the heating!"; heatingStatus = "on"; fanStatus = "off"; } else if(temperature > 72){ message = "Turn on the fan!"; heatingStatus = "off"; fanStatus = "on"; } else { message = "Temperature is OK"; heatingStatus = "off"; fanStatus = "off"; }
The switch Statement
When we’re testing for a range of different possible outcomes of the same conditional statement, a concise syntax we can use is that of JavaScript’s switch statement:
switch(color) { case "red" : message = "Stop!"; break; case "yellow" : message = "Pass with caution"; break; case "green" : message = "Come on through"; break; default : message = "Traffic light out of service. Pass only with great care"; }
The keyword switch has in parentheses the name of the variable to be tested.
The tests themselves are listed within the braces, { and }. Each case statement (with its value in quotes) is followed by a colon, then the list of actions to be executed if that case has been matched. There can be any number of code statements in each section.
Note the break statement after each case. This jumps us to the end of the switch statement after having executed the code for a matching case. If break is omitted, it’s possible that more than one case will have its code executed.
The optional default case has its code executed if none of the specified cases were matched
Logical Operators
There will be occasions when we want to test a combination of criteria to determine whether a test condition has been met, and doing so with if ... else or switch statements becomes unwieldy.
Let’s return once more to our temperature control program. JavaScript allows us to combine conditions using logical AND (&&) and logical OR (||). Here’s one way:
if(temperature >= 64 && temperature <= 72) { message = "The temperature is OK"; } else { message = "The temperature is out of range!"; }
We can read the preceding condition as “If the temperature is greater than or equal to 64 AND the temperature is less than or equal to 72.”
We can achieve exactly the same functionality using OR instead of AND:
if(temperature < 64 || temperature > 72) { message = "The temperature is out of range!"; } else { message = "The temperature is OK"; }
Here we have reversed the way we carry out the test; our conditional statement is now fulfilled when the temperature is out of range, and can be read as “If the temperature is less than 64 OR greater than 72.”