Home > Articles

This chapter is from the book

Control Statements

Control statements are designed to allow you to create scripts that can decide which lines of code are evaluated, or how many times to evaluate them. There are two different types of control statements: conditional statements and loop statements.

Control statements make their decisions based on an expression that evaluates to the logical values true or false or their equivalents in other data types. As we will be using non-boolean data types extensively for the remainder of the chapter, here is a reminder of how the other data types are treated in logical conditions:

  • Numbers are treated as true if not equal to 0, otherwise they are treated as false

  • Strings are treated as true if greater than 0 characters in length, otherwise they are treated as false

  • undefined is treated as false

  • null is treated as false

Conditional Statements

Conditional statements are used to make decisions. In real life, we make all sorts of decisions based on criteria such as "am I being offered enough money to take this job?" If the answer is "yes," then the result is "take the job." If the answer is "no," then "don't take the job." In JavaScript, you need to make decisions about which sections of code to evaluate. For example, if you asked a user for input so you could perform a calculation, you will want to carry out the calculation if the input is numeric, but not if it isn't.

You already have come across a simple means of making a decision in the form of the conditional operator, ?:. The conditional operator checks to determine if a condition is true or false, and uses the result to decide whether to evaluate to its second or third operand. Although this is a quick method of assigning one of two values to a variable, it is also very limited. If you want to choose between more than two options, the conditional operator is inadequate to do what you want.

The if, else, and else if Statements

The if, else, and else if statements allow you to make a choice among several options. First let's look at how to use the if statement to make a choice between two alternatives.

The if statement is the most frequently used decision-making statement. It checks a condition and if it evaluates to true, then the statement(s) that it governs are evaluated, but if it evaluates to false then the statement(s) are passed over. The syntax is as follows:

if (condition) statement


if (condition)

The condition is always surrounded by parentheses but the statement it governs can be on the same line or the following line. The JavaScript interpreter always associates the if statement with whatever statement follows it. Both code layouts work but some people prefer using separate lines because it makes their if statements easier to read. Here is an example that uses two if statements so you can get a feel for how the if statement works:

var myVar1 = true;
var myVar2 = false;
if (myVar1 == true) alert("myVar1 is true");
if (myVar2 == true) alert("myVar2 is true");

This will display only one alert box. The final line in the code will not cause an alert box to be displayed because the variable myVar2 has the value of false. See Figure 3.7.

Figure 3.7 The first if statement evaluates to true so the first alert box displays.

Remember that the comparison operator, ==, checks to see if the operands to its right and left are equal. If they are equal it returns true, and if they are not equal it returns false. In the above example, the condition for the first if statement evaluates to true because the value of myVar1 is true. The condition for the second statement evaluates to false because myVar2 does not equal true. As you can see, the if statement makes the decision as to whether the alert() function is called based on the evaluation of the condition.

Frequently, you will want the if statement (and the other conditional statements for that matter) to govern more than just one other statement. To do this, you need to use what is known as a statement block. The statement block consists of a pair of curly braces that surround the if statement's statements in the same way that curly braces surround the statements in the function body. For example:

if (condition) {

Hopefully this feels familiar. If the condition in parentheses evaluates to true, then the statements within the curly braces are evaluated. If the condition in parentheses evaluates to false, then none of those statements is evaluated.


It is useful to use curly braces even when the if statement has only one statement associated with it. Then if you later need to add other statements, you won't encounter errors caused by forgetting to add the curly braces.

Remember that conditional statements allow you to take one action if a condition is true and another if it isn't. This is where the else statement comes in. By placing the else statement after the if statement, it is linked to the if statement so that the statement(s) it governs is evaluated if the condition in the parentheses of the if statement turns out to be false. This saves writing out the condition again. In this way, either the statements the if statement governs will be evaluated, or the statements the else statement governs will be evaluated. After all a condition in JavaScript can only evaluate to true or false. Here are a couple of examples to demonstrate how you would write this:

if (4 < 3)
  alert("4 is less than 3");
  alert("4 is greater than 3");

Since 4 is greater than 3, the alert after the if statement is ignored; therefore, the alert() function after the else statement is evaluated. The else statement can also be used with a function block so you could write:

if (4 < 3) {
 alert("The if statement's statement block was evaluated");
 alert("because 4 is less than 3");
else {
 alert("The else statement's statement block was evaluated")
 alert("because 4 is greater than 3")

Finally, when you need even more flexibility to check multiple conditions there is the else if statement. It is inserted between the if and else statements. Here's an example:

var promptVal = prompt("Please enter a number", "");

if (promptVal > 0)
  alert("The number you entered was positive");
else if (promptVal == 0)
  alert("The number you entered was zero");
  alert("The number you entered was negative");

In this example, the script accepts an inputted number and uses it along with the if ... else if ... else statements to choose among three possible alerts to evaluate. Note that only one of the control statements will be used. If the if statement's condition evaluates to true, then the else if statement and the else statement will be ignored. If the if statement evaluates to false, then the condition of the else if statement is checked. Likewise if the condition of the else if statement evaluated to true, then the else statement would be ignored. The else statement acts as the default if all the previous conditions evaluated to false. Sometimes you will not want anything to happen if none of your conditions evaluates to true, in which case you would not use an else statement.

Multiple else if statements can be placed between the if statement and else statement if you want to check for more than three conditions.

If you remember the discussion about the isNaN() function earlier, you may have realized that there is a problem with the example above—it doesn't allow for the fact that the user may enter a non-numeric value. To accommodate this situation, you would want to move the condition checking for a number greater than 0 to an else if statement and use the if statement to first check if the value entered is numeric. To do this you would use the isNaN(). Here's an example:

var promptVal = prompt("Please enter a number", "");

if (isNaN(promptVal))
  alert("That wasn't a number!");
else if (promptVal > 0)
  alert("The number you entered was positive");
else if (promptVal == 0)
  alert("The number you entered was zero");
  alert("The number you entered was negative");

Note that statement blocks also can be used with the else if statement to control more than just one statement, such as the alerts in the earlier example.

Let's look next at an alternative control statement, the switch statement, that could have been used instead of the if...else statements in the above example.

The switch Statement

The switch statement allows you to choose one of several options. It has functionality which resembles that provided by the if, else if, and else statements. Let's look at how the switch statement works.

The switch statement has markedly different syntax from the if...else statements, but it works in a similar way. Its structure is shown below. Note that the lines that begin with case must end in a colon.

switch (expression){
 case value:
 case value:
 case value:


Case values in JavaScript do not need to be constants or the same data type.

The first thing a switch statement does is evaluate the expression contained within its parentheses to a single value. It then works its way down through the case statements checking if the value returned by the expression in parentheses after the switch keyword is matched by any of the values that follow the case keywords. If it finds a match, then it evaluates all the following statements that belong to that case statement.

Try the example in Listing 3.5, and see for yourself.

Listing 3.5 Switch Statement Demo (switchDemo.htm)

<title>Switch Statement Demo</title>

<script language="javascript" type="text/javascript">

switch (1+1){
 case "a":
 case 2:
 case true:



<h1>Switch Statement Demo</h1>


This page will result in the alert boxes shown in Figure 3.8.

Figure 3.8 Two alert boxes are brought up because the second and third case statements each evaluate as true.

This is because the 1+1 evaluates to 2. Therefore it should come as no surprise that the first case, the string "a", does not cause the associated alert() function to be evaluated. But the next case is the number 2, which is a match. As you can see from the screenshots in Figure 3.8, this causes not only the alert containing the number 2 to be evaluated, but, perhaps surprisingly, the alert containing the number 3 is also displayed. However, this may come as no surprise. We did say that if a match was found all the following statements would be evaluated up to the closing curly brace of the switch statement. Although this feature can occasionally be of use, generally you will want to evaluate only the statements between the matching case and the following one. To do this, you need to use the break statement. Replace the switch statement in Listing 3.5 with the following code:

switch (1+1){
 case "a":
 case 2:
 case 3:


The statements following each case are not enclosed in curly braces as in a statement block even if there are lots of them on multiple lines. Therefore, it is helpful to lay out your code as shown in the example above, to help you or someone else decipher your code.

As you will see, using the break statement as the last statement in a case statement block breaks off evaluation of the switch statement, and execution of the script continues after the closing curly brace of the switch statement. This has the desired effect of preventing the statements belonging to the other case statements from being evaluated.

The switch statement is able, optionally, to run some code in the event that there are no matches—just as a concluding else statement works at the end of an if...else statement. To do this, you would include, following the case statements, the keyword default followed by a colon, as shown in the example below:

switch ("Match this string."){
 case "This doesn't match.":
  alert("This would have alerted if it had!");
 case "Nor does this.":
  alert("This would have alerted if it had!");
 case "Or this.":
  alert("This would have alerted if it had!");
  alert("None of the cases matched so the default evaluated.");

As none of the cases above are the string "Match this string", their statements are ignored and the statements under the default are evaluated. See Figure 3.9.

Figure 3.9 The default statement is evaluated when none of the case statements match.

So which should be used: the if...else statement or the switch statement? The answer is that often either will do. The switch statement checks for a match to a single expression, and therefore is useful when you need to evaluate different statements based on the value of a single variable. It is also more efficient, so try to become accustomed to using it when possible. The if...else statement, on the other hand, can be given a new condition to check with each else if statement. This gives the if statement (and its associated else if statements) more flexibility, so the if statement tends to be used more than the switch statement.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020