CIT190 - JavaScript Programming

Key Concepts - Chapter 4 Decisions and Loops


Overview

This chapter covers the building blocks of programming:  sequence, selection and repetition.  All programming languages utilize these 3 buildling blocks to create code. 

Sequence is built into programs because they are executed from top to bottom  (you don't have to do anything special, because that control structure is already there)

Selection (decisions) and repetition (loops) have several variations and situations where the use of one structure is better than another.  We will be working with each type of structure, their variations and the JavaScript code necessary to produce them.

Both selection and repetition structures use conditional testing.  We will quickly review comparison and logical operators and then we will get into decision making and looping.

A  Review of Comparison and Logical Operators

To see a video summary, watch: https://youtu.be/46eeyBeMsV0

1.  Comparison Operators

Comparison operators compare two variables for equality and they can also determine if one value is greater than the other.

Comparison operators include:

== returns true if both variables are equal

Example:
var year1 = 2018;
var year2="2018";

if (year1 == year2)
      document.write("<br>The values are  the same");
else
      document.write("<br>The values are NOT the same");


Here's the example live:

=== returns true if both variables are equal AND they have the same data type

Example:
var year1 = "2018";
var year2=2018;

if (year1 === year2)
      document.write("<br>The values and data types are  the same");
else
      document.write("<br>The values and data types are NOT the same");


Here's the example live:

!= returns true if the variables are not equal

Example:
var num1 = 100;
var num2="100";

if (num1 != num2)
     document.write("<br>The numbers are not the same");
else
      document.write("<br>The numbers are the same");


Here's the example live:

!== returns true if the variables AND data types are not equal

Example:
var num1 = 100;
var num2 = "100";

if (num1 !== num2)
     document.write("<br>The numbers are not the same");
else
      document.write("<br>The numbers are the same");


Here's the example live:

> returns true if the left operand is greater than the right

Example:
var num1 = 100
var num2=50

if (num1 > num2)
      document.write("<br>"+num1+" is greater than "+num2);
else
      document.write("<br>"+num1+" is less than "+num2);


Here's the example live:

< returns true if the left  operand is smaller than the right
>= returns true if the left operand is greater than or equal to the right operand
<= returns true if the left  operand is smaller than or equal to  the right operand

2.  Logical Operators

JavaScript includes logical operators that can be used to create more complicated conditions.

These operators are:

    1. && (logical AND) – both conditions must be true for the equation to be true

      Example: if (pay_type == "h" && hours > 40)


      Try it live:

      Enter pay type(h=hourly, s=salary, p=piecerate):

      Enter hours:

       
    2. || (logical OR) – only one of the conditions must be true for the equation to be true

      Example: if (pay_type == 1 || pay_type == 2 || pay_type == 3)

      Try it live:

      Enter pay type:

       
    3. ! (logical NOT) – this is a unary operator because it checks a single condition.  It returns the opposite of what would normally return (if the value was true, it would return false). 

      Example: if  (!(numEntered%2==0))
    4. Try it live:

      Enter a number:

NOTE: Any expression that produces a value of zero is considered false and any expression that produces a nonzero value is considered true.

To learn more about comparison and logical operators and work with live examples, visit:  http://www.w3schools.com/js/js_comparisons.asp  

B.  Selection Structures:

To see a video overview, watch: https://youtu.be/m8Xn0eGZMlI

Decision-making structures are used to check conditions and specify actions based upon those conditions or to choose an action from multiple options.

There are 3 different types of decision-making structures you can use in JavaScript: 

1) if; 

2) if/else; 

3) switch. 

1.  if statement

This is a single-sided selection structure because it selects a single set of actions. The action(s) are only performed if the condition it tests is true.

Syntax:

if (condition)
     action statement;

Programming Example:

var hours = prompt("Enter the number of hours worked: ");
var overtimehours = 0;
if ( hours > 40 )
   overtimehours = hours – 40 ;
 

NOTE: 

a)  When writing an if statement in JavaScript, make sure you indent the action to make the code easier to read. 
b)  Use a lowercase "i" in the word if
c)  Do NOT put a semicolon after the condition (only put the semicolon after action statements)

JavaScript  allows multiple actions when conditions are true or false. If you want to execute more than one action statement, the statements must be enclosed in braces. When a group of statements is enclosed by braces, they are referred to as a command blocks or  compound statements.

Syntax:

if(condition) {
    action1;
    action2;
    action3;
    action n;
}

Programming Example:

if ( hours > 40 ) {
   overtimehours =(hours – 40 ;
   pay = (40 * payrate) + (overtimehours *(1.5 * payrate));
}
document.write("<br>You received $"+pay);

NOTE:  In the if statement, overtime and pay will only be calculated if the hours are greater than 40.  Once they are calculated, the document.write statement will be executed.  If the hours condition is false it won't do anything (it will skip the statements following the if).  Control will go to the document.write statement (it isn't part of the if statement).

2.  If/else statement

This is a double-selection structure because it selects between two different sets of actions. The first action or set of actions is performed when the condition is true and the second set is performed if the condition is false.

Syntax:

if (condition)
   action performed when condition is true;
else
   action performed when condition is false;

Programming Example:

if ( hours > 40 ) {
   overtime = (hours – 40) * (1.5*reg_pay);
   total_pay = (40 * reg_pay) + overtime;
   }
else
   total_pay = reg_pay * hours;

document.write("<br>Your pay is: "+total_pay);

When you use the if/else statement, you have to specify some type of code to represent actions if the condition is true and another section of code if the condition is false.  If you don’t want any type of action executed, then you can enter a semicolon on the action line.

 Programming Example:

if ( hours > 40 ) {
   overtime = (hours – 40) * (1.5*reg_pay);
   total_pay = (40 * reg_pay) + overtime;
   }
else
  ;

In this example, nothing would happen if the condition was false.

To learn more about If...Else Statements and work with live examples, visit:  https://www.w3schools.com/js/js_if_else.asp

3.  Nested if/else

There may be instances when programmers want to check a condition and then if the result is true, they want another condition checked (or if the condition is false, another condition should be checked).   This type of situation requires "nested" if statements.   There are two different ways you can code nested if statements:

Syntax Method 1:

if (condition)
   action performed when condition is true;
else  if (condition)
      action performed when condition is true;
   else if (condition)
        action performed when condition is true;
   else
        action performed when condition is false;
 

Syntax Method 2:

if (condition)
   action performed when condition is true;
else 
    if (condition)
        action performed when condition is true;
    else
       if (condition)
            action performed when condition is true;
       else
            action performed when condition is false;
 

3.  Switch statement

If you have a condition that requires several different alternate courses of action, then you should use the switch selection structure.

Syntax for a numeric variable:

switch (variable name) {
   case 20:
       action;
       action;
       action;
       action;
       break;
   case 100: case 200:
       action;
       action;
       break;
   case 400:
       action;
       action;
       break;
   default:
       action;
       break;
   }

Syntax for a character variable:

switch (variable name) {
   case ‘x’:
      action;
      action;
      action;
      action;
      break;
   case ‘y’: case ‘z’:
      action;
      action;
      break;
   case 'a':
      action;
      action;
      break;
  default:
      action;
      break;
   }

NOTE: When using a character variable, the values must be enclosed in single quotes. Otherwise, all rules that apply to numeric variables also apply to character values.

Syntax for a string variable:

switch (variable name) {
   case "string1":
      action;
      action;
      action;
      action;
      break;
   case "string2": case "string3":
      action;
      action;
      break;
   case "string4":
      action;
      action;
      break;
  default:
      action;
      break;
   }

NOTE: When using a string variable, the values must be enclosed in double quotes. Otherwise, all rules that apply to numeric and character variables also apply to string values.

IMPORTANT:  Since JavaScript is a loosely typed language, it allows one variable to take on values with different data types.  You can code this into your switch case labels using a combination of the rules above:

Syntax for mixed variables:

switch (variable name) {
   case "string1":
      action;
      action;
      action;
      action;
      break;
   case ‘a’: case ‘b’:
      action;
      action;
      break;
   case 200:
      action;
      action;
      break;
  default:
      action;
      break;
   }

SIDE NOTE:  Most programming languages do NOT allow this!

To learn more about switch statements and work with interactive examples, visit:  https://www.w3schools.com/js/js_switch.asp

C.  Repetition Structures:

Repetition structures are used to repeat the same sequence of code over and over for a set number of repetitions or until a particular condition is met.

JavaScript uses 4 types of repetition structures.  The first three structures are used in traditional programming and work with any variable.  The fourth structure, for/in, is used to access the properties of an object.

1) while; 

2) do/while; 

3)  for

4)  for/in

To learn more about repetition structures and work with live examples, visit: https://www.w3schools.com/js/js_loop_for.asp

1.  while statement

To see a video summary,watch: https://youtu.be/mMsO_jAlBlk

Specifies that code should be repeated until a condition tests false. Once the condition tests false, control is passed to the next statement in the sequence below the while loop.

Syntax:

while (condition) {
   action;
   action;
   action;
   action;
   }

There are several techniques programmers use to create while loops.  If you know the number of times you want the code executed, you can use a counter-controlled repetition loops.   If you don't know the number of times a loop should execute, the user typically needs to enter a value that terminates the loop.  Ther terminating character is called a sentinel. 

a). Counter-Controlled Repetition

This technique uses a counter to specify the number of times a set of statements should execute. Repetition terminates when the counter exceeds the set limit. This is called definite repetition because the number of times the while loop will be executed is known.  (Each repetition of the loop is called an iteration).

IMPORTANT:  It is critical that you increment (or decrement) the counter so that it eventually tests false.  If you forget to do this, the loop will never end (you will have an infinite loop).

Programming example:  The while loop will execute 5 times.  Once the counter goes to 6, the loop will terminate and the alert statement will execute.

<script>
var itemcost=0;
var item;
var totcost=0;
var counter = 1;
while (counter <= 5){
    itemcost = prompt("Enter the item cost and it will be added to the total: ");
    item = Math.ceil(itemcost);
    totcost += item;
    counter++;
}
alert("The total cost of all items is: "+totcost);
</script>

NOTE:  Math.ceil is a math method that converts the string number input from the prompt statement into a real number that can be used in calculations. 

To see the program live, view: definite_repetition.html

b). Sentinel-Controlled Repetition

This technique is used when the number of entries is unknown. It allows users to enter a number or value that causes the while loop to terminate. The value that users enter is often called a flag-value, dummy value, signal value or sentinel value. This is called indefinite repetition because the number of times the while loop will be executed is unknown before looping begins.

The sentinel value selected by the programmer must be fairly unique (it cannot be confused with data the user will input). For that reason, many programmers choose negative numbers such as –1.  The while loop will continue while the input value is not equal to –1.

IMPORTANT:  At the bottom of the while loop, you need to ask the user if they want to continue and then read in the value they enter - this is the value that should be tested in the while loop.  If you forget to read in a value, then you will have an infinite loop.

Programming example:  The while loop will continue executing until the user types a n at the prompt at the bottom of the loop.  The value for go is initially set to y so the user goes through the loop 1 time.  After the loop is entered, the value for go is reset at the bottom (the value returned from prompt is placed into go). 

<script>
var itemcost=0;
var item;
var totcost=0;
var go = 'y';  // this is the sentinel
while (go != 'n'){
    itemcost = prompt("Enter the item cost and it will be added to the total: ");
    item = Math.ceil(itemcost);
    totcost += item;
    go = prompt("Enter a n to stop, press any key to continue:");
}
alert("The total cost of all items is: "+totcost);
</script>

To see the program run live, view: indefinite_repetition.html

c).  Summary of repetition controls:

  1. Counter-controlled repetition

++counter;

counter++;

counter = counter + 1;

counter +=1;

  1. Sentinel-controlled repetition

2.  do/while statement

To see a video summary, watch: https://youtu.be/GgIJb6hrAPA

The while structure tests the condition before executing the loop. The do/while structure tests the condition after the loop has been executed. This ensures that the loop is executed at least one time.

Syntax:

do {
   action;
   action;
   action;
} while (condition);

NOTE: Even if you only have 1 action statement after the do, you should include the braces (it makes it easier to follow and helps distinguish it from the while structure.

Programming Example:

<script>
var itemcost=0;
var item;
var totcost=0;
var go = 'y';

do{
    itemcost = prompt("Enter the item cost and it will be added to the total: ");
    item = Math.ceil(itemcost);
    totcost +=item;
    go = prompt("Enter a n to stop, press any key to continue:");
} while (go != 'n')

alert("The total cost of all items is: "+totcost);
</script>

To see the example live, view: do-while-indefinite-repetition.html

For more information on while and do/while loops, visit:  https://www.w3schools.com/js/js_loop_while.asp

3.  for statement

To see a video summary, watch: https://youtu.be/kDXjMdyxrKc

Within one statement, the for structure handles initializing the counter, checking the condition and incrementing the counter.

Syntax:

for ( expression1; expression2; expression3)
   Action as long as the condition is true;

Another syntax example with a counter variable:

for (counter = # ; counter<= # ; counter++) {
    action1;
    action2;
    actionn;
}

Where # is whatever digit you designate ( it can also be an equation).

Example #1:   The variable being checked (counter) is defined and initialized inside the for loop

var total=0;
for (var counter=1; counter <10; counter++)
    total+=counter;
document.write("<br>The total is: ",total);
 

Example #2:   The variable being checked (counter) is defined and initialized above the for loop

var total=0;
var counter=0;
for (; counter <10; counter++)
    total+=x;
document.write("<br>The total is: ",total);

Example #3:  The example below uses the decrement operator.  The loop will continue until the counter reaches 0 

for (counter = 100; counter > 0; counter--)
   total += counter;

All the examples above involve incrementing (or decrementing) a counter within a for statement.   You can also include calculations within a for statement. Calculations involving the counter should be placed in the expression3 slot where you also increment the counter. You can have multiple expressions here – each one must be separated by a comma.

Example: In this example, the total calculation has been moved into the for loop.

for (var counter = 100; counter >= 0; total+= counter, counter--)

For loops are typically used to read data from arrays or to place data into arrays (the comments in the program explain how the counters are being used.)

Programming Example:

<script>
var foods=[];
var n = prompt("How many foods do you want to enter?");
var number = parseInt(n);
// filling foods array
for (var counter=0; counter<number; counter++){
    foods[counter]=prompt("Enter a favorite food or dish: ");
}
// printing from array
for (var counter2=0; counter2<number; counter2++){
    document.writeln("<p>" + foods[counter2] + "</p>");
}
</script>

A TYPICAL ERROR when working with loops is the off by one error.  This happens when the counter is initialized and incremented but the loop either executes 1 too many times or 1 too few times. 

For more information on for loops and to try interactive examples, visit:  https://www.w3schools.com/js/js_loop_for.asp

4.  For/In Loops

To see a video summary, watch: https://youtu.be/5hQsigBxdgY

When using a for/in loop, you need to specify a variable that will act as a subscript.  Then, you can subscript into the object and retrieve the property values stored.  You don't need a counter or a sentinel.  JavaScript will automatically include all properties and values for you.

Example:

<script>
var Pet= {
    name:prompt("Enter the name of your pet: "),
    breed:prompt("Enter the breed of your pet: "),
    color:prompt("Enter the color of your pet: "),
};
document.writeln("<p>Here are the properties of your object: </p>");
for (x in Pet){
    document.writeln("<p>" + Pet[x] + "</p>");
}
</script>

To see the example live, view: for-in-loop-example.html

D.  More about break and continue:

Both the break and continue statements are used to alter the flow of control within a program.

Break can be used in while, for, do/while or switch structures. It causes immediate exit from the structure and program control goes to the first statement after the structure.

Continue can be used in while, for and do/while structures. It skips remaining statements in the body of the structure and performs the next iteration of the loop. In while and do/while structures, it tests the condition. In the for structure, it increments the counter and then does the conditional test.

For more information on break and continue statements and to try interactive examples, visit: https://www.w3schools.com/js/js_break.asp

E.  More on type conversion:

JavaScript is a "loosely typed" language, which means that whenever an operator or statement is expecting a particular data-type, JavaScript will automatically convert the data to that type.

In an if statement, the condition results in a boolean value, therefore whatever you define in the brackets will be converted to a boolean. The same is true for while() and do...while() statements.

 JavaScript values are often referred to as being "truthy" or "falsey", according to what the result of such a conversion would be (i.e. true or false).

There are only six falsey values:

Everything else is truthy  (this includes a "0" (string zero), all objects and all constructors.

The table below illustrates how the type conversions work:

javascript type conversion example
javascript type conversion example - part2
Retrieved from https://www.w3schools.com/js/js_type_conversion.asp, August 2018

For more information on type conversion visit: https://www.w3schools.com/js/js_type_conversion.asp  

1.  Assignment Statement Using Logical Operators

We can take what we know about type conversion and logical operators and apply this knowledge to create an assignment statement that checks multiple values before assigning a default value to a variable.

JavaScript will check the first variable to see if it contains a value (to see if it is "true")   If it contains a value, that one will be used.  If it doesn't contain a value, it will check the next variable, it will continue doing this until it finds a value OR it reaches the default value.

In the example below,  Hershey will only be assigned if selection1 and selection2 are empty

favoriteChocolatier = selection1 || selection2 || "Hershey";