Decision Making in JavaScript
References
Introduction
In your JavaScript programs, you will often need to run different sets of statements, based on certain conditions and criteria that are experienced in the code. Some of the types of conditions and criteria that your code may need to be aware of are:
- Time of day
- Day of the week
- User input
- What button was clicked
- What form fields were filled in or not
- etc.
- etc.
The process of determining the order in which statements run in a program is called decision making or flow control. JavaScript has built-in statements (keywords) called decision-making (flow control) structures. We will look at if and switch statements this week, and repetition (looping) statements in another week or two.
if Statements
Probably the most common flow control statement you will use will be the if statement. The if statement runs specified code if a conditional expression returns true.
The syntax for the if statement is
if (conditional expression)
{
a statement;
another statement;
}
You should note these points about this syntax:
- The statement starts with the if keyword.
- The conditional expression is enclosed within parentheses. Please see the NOTE below regarding combining conditions in the conditional expression.
- The code that is run if the conditional expression is true is enclosed within curly braces ( { and } ). The braces are not needed if only one statement is run, but I highly recommend that you always use the braces. The statements and the braces are often referred to as a command block.
That last item in the list above brings us to
Jim's Rule of Survival:
Always use curly braces in if-else statements.
We will see examples of how this rule can save your sanity as we go through the rest of this handout. (And, of course, there is an exception to Jim's Rule, in the section on multiple if...else statements.)
If the conditional expression evaluates to false, the code in the command block is skipped, and the next statement (if there is one) after the if statement's command block is run. This means, of course, that if the conditional expression evaluates to true, then the code in the command block runs, followed by any statements following the command block.
Here is some sample code to show how an if statement is used:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>if statement</title>
</head>
<body>
<div id="mainDiv">
<h3>This is a sample of an <i>if</i> statement.</h3>
<br />
<br />
<script type="text/javascript">
/* <![CDATA[ */
var exampleVar = prompt("Please enter an integer.","");
if (exampleVar == 5)
{
document.write("The variable is equal to 5.<br />");
}
document.write("<br />This code is after the if statement.");
/* ]]> */
</script>
</div>
</body>
</html>
The above code can be seen running here.
Combining Conditions in the Conditional Expression
As we saw in the handout on Data Types and Operators, it is possible to combine conditions in a conditional expression, using the Logical Operators. The general syntax for combining conditions is this:
((condition 1) [LO] (condition2))Please note these points about the above syntax:
- The "[LO]" is my shorthand for "Logical Operator". Recall that
the Logical Operators are these:
- && (AND)
- || (OR)
- ! (NOT)
- Each separate condition is enclosed in its own set of parentheses.
- The entire conditional expression is enclosed in an outer set of parentheses.
Here is a sample of some code to show how you can combine conditions in the conditional expression:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>Combined Conditions</title>
</head>
<body>
<div id="mainDiv">
<h3>This is a sample of <i>combined conditions</i>.</h3>
<br />
<br />
<script type="text/javascript">
/* <![CDATA[ */
var number = prompt("Please type in a number","");
if ((number > 0) && (number < 100))
{
document.write("The number is between 0 and 100.");
}
/* ]]> */
</script>
</div>
</body>
</html>
The above code can be seen running here.
if...else Statements
You can add an else statement to your if statement so you can specify one set of code to run if the conditional expression evaluates to true and another set of code to run if the conditional expression evaluates to false.
The syntax for the if...else statement is
if (conditional expression)
{
a statement;
another statement;
}
else
{
yet another statement;
even another statement;
}
If the conditional expression evaluates to true, the code in the first command block is run. If the conditional expression evaluates to false, the code in the second command block is run. And in either case, after one set of statements in the command blocks is run, then any statements following this entire if...else statement are run.
Here is some sample code to show how an if...else statement is used:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>if...else statement</title>
</head>
<body>
<div id="mainDiv">
<h3>This is a sample of an <i>if...else</i> statement.</h3>
<br />
<br />
<script type="text/javascript">
/* <![CDATA[ */
var today = new Date();
var dayOfWeek = today.getDay();
if (dayOfWeek == 6)
{
document.write("Today is Saturday.");
}
else
{
document.write("Today is NOT Saturday.");
}
document.write("<br /><br />This code is after the if statement.");
/* ]]> */
</script>
</div>
</body>
</html>
The above code can be seen running here.
Nested if Statements
Often in your JavaScript code, you will need to make other decisions in the command blocks that are run by if or if...else statements. You can make these further decisions with other if or if...else statements. These additional if and if...else statements, within an if or if...else statement, are called nested if statements.
If you use else statements in nested situations, you need to be aware that an else statement belongs to (is paired with) the closest if statement. Your indenting, carriage returns, and white space have nothing to do with how the else statements are paired with their if statement.
For example, the following code probably does NOT do what you intended:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>Nested if Statement</title>
</head>
<body>
<div id="mainDiv">
<h3>This is a sample of a <i>nested if</i> statement.</h3>
<br />
<br />
<script type="text/javascript">
/* <![CDATA[ */
var number = prompt("Please enter a number.","");
var numberRange;
if (number > 5)
if (number > 10)
numberRange = "The number is greater than 10.";
else
numberRange = "The number is less than 5.";
document.write(numberRange);
/* ]]> */
</script>
</div>
</body>
</html>
and you can see the results here.
You probably actually meant to write this code:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>Nested if Statement</title>
</head>
<body>
<div id="mainDiv">
<h3>This is a sample of a <i>nested if</i> statement.</h3>
<br />
<br />
<script type="text/javascript">
/* <![CDATA[ */
var number = prompt("Please enter a number.","");
var numberRange;
if (number > 5)
if (number > 10)
numberRange = "The number is greater than 10.";
else
numberRange = "The number is less than or equal to 10.";
else
numberRange = "The number is less than or equal to 5.";
document.write(numberRange);
/* ]]> */
</script>
</div>
</body>
</html>
and you can see the results here.
You can force the first version of this code to do what you want by using curly braces, which I said that you should always do anyway, like this:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>Nested if Statement</title>
</head>
<body>
<div id="mainDiv">
<h3>This is a sample of a <i>nested if</i> statement.</h3>
<br />
<br />
<script type="text/javascript">
/* <![CDATA[ */
var number = prompt("Please enter a number.","");
var numberRange = "";
if (number > 2)
{
numberRange += "<br>The number is greater than 2.";
if (number > 5)
{
numberRange += "<br>The number is greater than 5.";
if (number > 10)
{
numberRange += "<br>The number is greater than 10.";
}
else
{
numberRange += "<br>The number is less than or equal to 10."
}
}
else
{
numberRange += "<br>The number is less than or equal to 5.";
}
}
else
{
numberRange += "<br>The number is less than or equal to 2.";
}
document.write(numberRange);
/* ]]> */
</script>
</div>
</body>
</html>
and you can see the results here.
And now here is a modified version of the last sample code in the section "Combining Conditions in the Conditional Expression", above. This modified version adds a test to see if the user typed in a number or not:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>Nested if Statements</title>
</head>
<body>
<div id="mainDiv">
<h3>This is a sample of an <i>if</i> statement.</h3>
<br />
<br />
<script type="text/javascript">
/* <![CDATA[ */
var numberStr = prompt("Please type in a number","");
var number = parseInt(numberStr);
if (isNaN(number))
{
document.write("You put some garbage in there.");
}
else
{
if ((number > 0) && (number < 100))
{
document.write(number + " is between 0 and 100.");
}
else
{
document.write(number + " is NOT between 0 and 100.");
}
}
/* ]]> */
</script>
</div>
</body>
</html>
The above code can be seen running here.
Please note these points about the modified version:
- The built-in method parseInt( ) converts a string to an integer number IF there is an integer number at the beginning of the string. Any decimal digits or letters following the number are dropped.
- parseInt( ) returns NaN (Not a Number) if there is something other than a number at the beginning of the string that it is converting.
- You cannot directly compare NaN with anything, even itself. The built-in method isNaN( ) returns true if the value being tested is NaN, otherwise it returns false.
Multiple if...else Statements
If you have many choices of actions based on many possible values of an expression, you can use multiple if...else statements in sequence. (In the next section, we will see the switch statement, which is often a better way to go.)
Please recall that if you have only one action to take after each condition, you do not need to use curly braces around the action statements, even in a multiple if...else situation. The choice is yours whether to use curly braces or not. Here is the syntax of a multiple if...else situation, without curly braces:
if (conditional expression 1)
statement 1;
else if (conditional expression 2)
statement 2;
else if (conditional expression 3)
statement 3;
else if (conditional expression 4)
statement 4;
else if (conditional expression 5)
statement 5;
else if (conditional expression 6)
statement 6;
else if (conditional expression 7)
statement 7;
else
statement 8;
Here is a sample of multiple if...else statements. Please note that the first statement in the function displayGreeting() retrieves the selected country's string value. For now, don't worry about how the string gets there. We'll look at select lists in more detail in the handout on "Forms". Okay, here is the code:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>multiple if...else statements</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<script type="text/javascript">
/* <![CDATA[ */
function displayGreeting()
{
var yourCountry = document.getElementById("CountryList").options[document.getElementById("CountryList").selectedIndex].value;
var msg = "";
if (yourCountry == "United States")
msg = "Howdy!";
else if (yourCountry == "Germany")
msg = "Guten Tag!";
else if (yourCountry == "Spain")
msg = String.fromCharCode(161) + "Buenos D" + String.fromCharCode(237) + "as!";
/* UTF 161 is upside-down explanation point */
/* UTF 237 is i-acute */
else if (yourCountry == "Mexico")
msg = String.fromCharCode(161) + "Buenos D" + String.fromCharCode(237) + "as!";
/* UTF 161 is upside-down explanation point */
/* UTF 237 is i-acute */
else if (yourCountry == "Italy")
msg = "Buon Giorno!";
else if (yourCountry == "France")
msg = "Bonjour!";
else
msg = "We don't know where you live!";
alert(msg);
}
/* ]]> */
</script>
</head>
<body>
<div id="mainDiv">
<form name="theForm" action="MultipleIfElse.html" method="post">
<select name="CountryList" id="CountryList">
<option value="">-- Select a Country --</option>
<option value="United States">United States</option>
<option value="France">France</option>
<option value="Germany">Germany</option>
<option value="Italy">Italy</option>
<option value="Mexico">Mexico</option>
<option value="Spain">Spain</option>
</select>
<br />
<br />
<input type="button" onclick="displayGreeting();" value="Display a Greeting..." />
</form>
</div>
</body>
</html>
You can see the above code running here.
The multiple if...else... statements in the above sample code are actually nested if statements. Perhaps this fact will be more apparent if we look at a version of the above code that includes the curly braces. This is page MultipleIfElse2.html:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>multiple if...else statements</title>
<script type="text/javascript">
/* <![CDATA[ */
function displayGreeting()
{
var yourCountry = document.getElementById("CountryList").options[document.getElementById("CountryList").selectedIndex].value;
var msg = "";
if (yourCountry == "United States")
{
msg = "Howdy!";
}
else
{
if (yourCountry == "Germany")
{
msg = "Guten Tag!";
}
else
{
if (yourCountry == "Spain")
{
msg = String.fromCharCode(161) + "Buenos D" + String.fromCharCode(237) + "as!";
/* UTF 161 is upside-down explanation point */
/* UTF 237 is i-acute */
}
else
{
if (yourCountry == "Mexico")
{
msg = String.fromCharCode(161) + "Buenos D" + String.fromCharCode(237) + "as!";
/* UTF 161 is upside-down explanation point */
/* UTF 237 is i-acute */
}
else
{
if (yourCountry == "Italy")
{
msg = "Buon Giorno!";
}
else
{
if (yourCountry == "France")
{
msg = "Bonjour!";
}
else
{
msg = "We don't know where you live!";
}
}
}
}
}
}
alert(msg);
}
/* ]]> */
</script>
</head>
<body>
<div id="mainDiv">
<form name="theForm" action="MultipleIfElse.html" method="post">
<select name="CountryList" id="CountryList">
<option value="">-- Select a Country --</option>
<option value="United States">United States</option>
<option value="France">France</option>
<option value="Germany">Germany</option>
<option value="Italy">Italy</option>
<option value="Mexico">Mexico</option>
<option value="Spain">Spain</option>
</select>
<br />
<br />
<input type="button" onclick="displayGreeting();" value="Display a Greeting..." />
</form>
</div>
</body>
</html>
You can see the above code running here.
switch Statements
One way to avoid having a lot of nested or multiple if statements is to use the switch statement. A switch statement runs a specified set of statements depending on the value of an expression or condition. The values that you want the switch statement to look for are coded as case labels, and when the expression's value matches a case label, the code following the matched label is run.
The syntax of a switch statement is like this:
switch (expression)
{
case label1:
statement;
statement;
break;
case label2:
statement;
statement;
break;
case label3:
case label4:
statement;
statement;
break;
default:
statement;
statement;
}
Please note these points about the above syntax:
- The entire switch statement's code is enclosed within curly braces.
- Each label is actually a literal value or a variable name.
- Each label is followed by a colon. This is a requirement of the syntax.
- You can have more than one label trigger a particular set of statements, as in the situation with label3 and label4 above. If either of the labels is matched by the expression, the code following the label(s) is run.
- You end each block of statements with a break statement. You do not use curly braces to enclose blocks of code to run if a label matches the expression. Instead, you simply list the statements that you want to run, and the break statement tells JavaScript to skip everything else in the switch statement. JavaScript then runs any statements following the switch statement.
- You code a default label to handle the possibility that none of your labels match the expression. If none of the labels match the expression, the code in the default block runs.
Here is a sample of a switch statement. This sample is the previous sample of multiple if...else statements, reworked with a switch statement. Again, please note that the first statement in the function displayGreeting() retrieves the selected country's string value. For now, don't worry about how the string gets there. We'll look at select lists in more detail in the handout on "Forms". Here is the code:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>switch statement</title>
<script type="text/javascript">
/* <![CDATA[ */
function displayGreeting()
{
var yourCountry = document.getElementById("CountryList").options[document.getElementById("CountryList").selectedIndex].value;
var msg = "";
switch (yourCountry)
{
case "United States":
msg = "Howdy!";
break;
case "Germany":
msg = "Guten Tag!";
break;
case "Spain":
case "Mexico":
msg = String.fromCharCode(161) + "Buenos D" + String.fromCharCode(237) + "as!"; /* UTF 161 is upside-down explanation point */
/* UTF 237 is i-acute */
break;
case "Italy":
msg = "Buon Giorno!";
break;
case "France":
msg = "Bonjour!";
break;
default:
msg = "We don't know where you live!";
}
alert(msg);
}
/* ]]> */
</script>
</head>
<body>
<div id="mainDiv">
<form name="theForm" action="SwitchStatement.html" method="post">
<select name="CountryList" id="CountryList">
<option value="">-- Select a Country --</option>
<option value="United States">United States</option>
<option value="France">France</option>
<option value="Germany">Germany</option>
<option value="Italy">Italy</option>
<option value="Mexico">Mexico</option>
<option value="Spain">Spain</option>
</select>
<br />
<br />
<input type="button" onclick="displayGreeting();" value="Display a Greeting..." />
</form>
</div>
</body>
</html>
You can see the above code running here.
The Conditional Operator
We took a brief look at the conditional operator in the handout "Data Types and Operators". Now let's look at it in a bit more detail.
The conditional operator has this syntax:
conditional expression ? expression1 : expression2;
If the conditional expression evaluates to true, expression1 is executed. If the conditional expression evaluates to false, expression2 is executed.
An example of a conditional operator expression is shown below:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>Conditional Operator Example 2</title>
<script type="text/javascript">
/* <![CDATA[ */
function reportClick(button)
{
var clickedButton;
(button.value == "First Button") ? clickedButton = "First and Best" : clickedButton = "Second";
alert("You clicked the " + clickedButton + " button.");
}
/* ]]> */
</script>
</head>
<body>
<div id="mainDiv">
<form name="theForm" action="" method="post">
<input type="button" value="First Button" onclick="reportClick(this);" />
<br /><br />
<input type="button" value="Second Button" onclick="reportClick(this);" />
</form>
</div>
</body>
</html>
and this code can be seen running here.
Please note these points about the above code:
- The keyword this that you see in both calls to the custom function reportClick() sends a reference to the tag that the function call is in, to the function. In this code, the tag is an input tag. (Technically, this refers to the JavaScript object that corresponds to the tag.)
- In the custom function reportClick(), the parameter button receives the object that corresponds to the tag that the function call was in.
- The property value that is in the button object (coded as button.value) is the string that is the value of the value attribute in the tag itself.
- The conditional expression that is in the custom function tests to see if the button value is "First Button". If so, the string "First and Best" is assigned to variable clickedButton. If not, the string "Second" is assigned to the variable.
You can accomplish exactly the same thing as what the conditional operator does, with a simple if...else statement, like this:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>Conditional Alternative</title>
<script type="text/javascript">
/* <![CDATA[ */
function reportClick(button)
{
var clickedButton;
if (button.value == "First Button")
{
clickedButton = "First and Best";
}
else
{
clickedButton = "Second";
}
alert("You clicked the " + clickedButton + " button.");
}
/* ]]> */
</script>
</head>
<body>
<div id="mainDiv">
<form name="theForm" action="" method="post">
<input type="button" value="First Button" onclick="reportClick(this);" />
<br /><br />
<input type="button" value="Second Button" onclick="reportClick(this);" />
</form>
</div>
</body>
</html>
You can see the alternative code running here.
Feel free to use whatever syntax you are most comfortable with. But also keep in mind that a lot of JavaScript programmers do like the conditional operator, so you will need to understand it if you see it. :-)