Home > Articles > Open Source > Ajax & JavaScript

This chapter is from the book

This chapter is from the book

6.2 Conditionals

Conditional constructs control the flow of a program. If a condition is true, the program will execute a block of statements and if the condition is false, flow will go to an alternate block of statements. Decision-making constructs (if, else, switch) contain a control expression that determines whether a block of expressions will be executed. If the condition after the if is met, the result is true, and the following block of statements is executed; otherwise the result is false and the block is not executed.

Format

if (condition){
  statements;
}

Example

if ( age > 21 ){
  alert("Let's Party!");
}

The block of statements (or single statement) is enclosed in curly braces. Normally, statements are executed sequentially. If there is only one statement after the conditional expression, the curly braces are optional.

6.2.1 if/else

"You better pay attention now, or else . . . " Ever heard that kind of statement before? JavaScript statements can be handled the same way with the if/else branching construct. This construct allows for a two-way decision. The if evaluates the expression in parentheses, and if the expression evaluates to true, the block after the opening curly braces is executed; otherwise the block after the else is executed.

Format

if (condition){
  statements1;
}
else{
  statements2;
}

Example

if ( x > y ){
  alert( "x is larger");
}
else{
   alert( "y is larger");
}

Example 6.1.

  <html>
    <head>
      <title>Conditional Flow Control</title>
    </head>
    <body>
      <h3>
1       <script type="text/javascript">
          <!-- Hiding JavaScript from old browsers
2         var age=prompt("How old are you? ","");
3         if( age >= 55 ){
4           document.write("You pay the senior fare! ");
5         }
6         else{
7           document.write("You pay the regular adult fare. ");
          }
          //-->
8       </script>
      </h3>
    </body>
  </html>

Explanation

1 JavaScript program starts here.

2 The prompt dialog box will display the message "How old are you?". Whatever the user types into the box will be stored in the variable age (see Figure 6.1).

3,4 If the value of the variable age is greater than or equal to 55, line 4 is executed (see Figure 6.2).

5 This closing curly brace closes the block of statements following the if expression. When there is only one statement in the block, the curly braces are not required.

6, 7 The else statement, line number 7, is executed if the expression in line 3 is false.

8 This tag marks the end of the JavaScript program.

Figure 6.1

Figure 6.1 The user is prompted for input.

Figure 6.2

Figure 6.2 If the age entered was greater than 55, this message is displayed.

The Conditional Operator

The conditional operator, called a ternary operator, was discussed in Chapter 5, "Operators." Because it is often used as a shortcut for the if/else conditional statement, it is reviewed again here.

Format

conditional expression ? expression : expression

Example

x ? y : z    If x evaluates to true, the value of the expression
              becomes y, else the value of the expression becomes z

big = (x > y) ? x : y     If x is greater than y, x is assigned to
                             variable big, else y is assigned to
                             variable big

An if/else statement instead of the conditional statement:

if (x > y) {
   big = x;
}
else{
   big = y;
}

Example 6.2.

  <html>
    <head>
      <title>Conditional Operator</title>
    </head>
    <body bgcolor="lightblue">
      <big>
      <script type ="text/javascript">
1       var age = prompt("How old are you? ", "");
2       var price = (age > 55 ) ? 0 : 7.50;
3       alert("You pay $" + price + 0);
      </script>
      </big>
    </body>
  </html>

Explanation

  1. The user is prompted for input. The value he or she enters in the prompt box is assigned to the variable age.
  2. If the value of age is greater than 55, the value to the right of the ? is assigned to the variable price; if not, the value after the : is assigned to the variable price.
  3. The alert dialog box displays the value of the variable price.

6.2.2 if/else if

"If you've got $1, we can go to the Dollar Store; else if you've got $10, we could get a couple of movies; else if you've got $20 we could buy a CD . . . else forget it!" JavaScript provides yet another form of branching, the if/else if construct. This construct provides a multiway decision structure.

Format

if (condition) {
  statement(s);
}
else if (condition) {
  statement(s);
}
else if (condition) {
  statement(s);
}
else{
  statement(s);
}

If the first conditional expression following the if keyword is true, the statement or block of statements following the expression is executed and control starts after the final else block. Otherwise, if the conditional expression following the if keyword is false, control branches to the first else if and the expression following it is evaluated. If that expression is true, the statement or block of statements following it are executed, and if false, the next else if is tested. All else ifs are tested and if none of their expressions are true, control goes to the else statement. Although the else is not required, it normally serves as a default action if all previous conditions were false.

Example 6.3.

  <html>
    <head>
      <title>Conditional Flow Control</title>
    </head>
    <body>
      <h2>
1       <script type="text/javascript">
          <!--
2         var age=eval( prompt("How old are you? ",""));
3         if( age > 0 && age <= 12 ){
4           alert("You pay the child's fare. ");
          }
5         else if( age > 12 && age < 60 ){
6           alert("You pay the regular adult fare. ");
          }
          else {
7           alert("You pay the senior fare! ");
          }
          //-->
8       </script>
      </h3>
    </body>
  </html>

Explanation

1

JavaScript program starts here.

2

The prompt dialog box will display the message "How old are you?". Whatever the user types into the box will be converted to a number by the eval() method and then stored in the variable age.

3, 4

If the value of the variable age is greater than 0 and age is also less than or equal to 12, then line 4 is executed and the program continues at line 8.

5, 6

If the expression on line 3 is false, the JavaScript interpreter will test this line, and if the age is greater than 12 and also less than 60, the block of statements that follow will be executed and control goes to line 8. You can have as many else ifs as you like.

7

The else statement, line number 7, is executed if all of the previous expressions test false. This statement is called the default and is not required.

8

This tag marks the end of the JavaScript program.

6.2.3 switch

The switch statement is an alternative to if/else if conditional construct (commonly called a "case statement") and may make the program more readable when handling multiple options.

Format

switch (expression){
case label :
  statement(s);
  break;
case label :
  statement(s);
  break;
  ...
default : statement;
}

Example

switch (color){
case "red":
  alert("Hot!");
  break;
case "blue":
  alert("Cold.");
  break;
default:
  alert("Not a good choice.");
  break;
}

The value of the switch expression is matched against the expressions, called labels, following the case keyword. The case labels are constants, either string or numeric. Each label is terminated with a colon. The default label is optional, but its action is taken if none of the other cases match the switch expression. After a match is found, the statements after the matched label are executed for that case. If none of the cases are matched, the control drops to the default case. The default is optional. If a break statement is omitted, all statements below the matched label are executed until either a break is reached or the entire switch block exits.

Example 6.4.

  <html>
    <head>
      <title>The Switch Statement</title>
    </head>
    <body>
      <script type="text/javascript">
        <!--
1       var day_of_week=Math.floor((Math.random()* 7)+1);
          // Get a random number between 1 and 7
          // Monday is 1, Tuesday is 2, etc.
2       switch(day_of_week){
3         case 1:
          case 2:
          case 3:
          case 4:
4           alert("Business hours Monday through Thursday are from
                   9am to 10pm");
5           break;
          case 5:
            alert("Business hours on Friday are from 9am to 6pm");
            break;
          case 6:
            alert("Business hours on Saturday are from
                   11am to 3pm");
            break;
6         default:
            alert("We are closed on Sundays and holidays");
7           break;
8       }
        //-->
      </script>
    </body>
  </html>

Explanation

  1. The random number function generates a random number between 1 and 7 inclusive when the script is executed. The random number is stored in a variable called day_of_week.
  2. The day_of_week value of the switch expression is matched against the values of each of the case labels below.
  3. The first case that is tested is 1. If the random number is 1, the message "Business hours Monday through Thursday are from 9am to 10pm" will be displayed in the alert dialog box. The same is true for case 2, 3, and 4.
  4. This statement is executed if case 1, 2, 3, or 4 are matched. Note there are no break statements associated with any of these 4 case statements. Program control just drops from one case to the next, and if cases 1, 2, 3, or 4 are not matched, execution control goes to the next case (case 5) for testing.
  5. The break statement causes program control to continue after line 8. Without it, the program would continue executing statements into the next case, "yellow", and continue doing so until a break is reached or the switch ends—and we don't want that. The break statement sends control of the program to line 8.
  6. The default statements are executed if none of the cases are matched.
  7. This final break statement is not necessary, but is good practice in case you should decide to replace the default with an additional case label.
  8. The final curly brace ends the switch statement. Figure 6.3 displays examples of the output.
    Figure 6.3

    Figure 6.3 A random number between 1 and 7 determines which is matched and executed.

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.

Overview


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.

Surveys

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.

Newsletters

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.

Security


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

Children


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

Marketing


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.

Choice/Opt-out


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.

Links


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