Sage-Code Laboratory
index<--

JS: Control Flow

It is time to discover control flow statements. This is a group of statements used to stear the logical flow of a script or program. A regular program is linear, but using control statements we can make alternative branches.We can select which branch is executed using control statements.

Bookmarks:

Decision Statement

The most useful control statement is the decision. This statement can create a fork in the program logic.This fork has one condition and two branches. The condition is a Boolean expressions. When the expression is evaluated to "true", first branch is executed. When condition becomes "false" the second branch is executed.Please study the diagram below and the example to understand better this statement:

decision

decision diagram

Example:
/* demo for "if" statement */
function greater(x, y) {
   let message
/* use conditional expression */
   if (x > y) {
      message = "yes! "+ `${x} is greater than ${y}`  // True branch
   } else {
      message = "no! " + `${x} is not greater than ${y}` // False branch
   }
   return message
}
/* call function with arguments */
console.log(greater(10,20)) // expected: no
console.log(greater(20,10)) // expected: yes

Notes:

Single branch: We can improve the code to show how a decision statement can work with just one branch.By using initial value "wrong" we asume that first parameter x is not greater than second parameter y.Then we test the condition and change the default value to "good" when the condition is true.This will simplify the function without loosing its logic. It will produce the same results as previous version.

/* demo for "if" statement */
function greater(x, y) {
   let message = "no"
   /* use conditional expression */
   if (x > y) {
      message = "yes"  // one branch
   }
   return message
};

/* call function with arguments */
console.log(greater(10,20)) // expected: yes
console.log(greater(20,10)) // expected: no

Switch Statement

Concept for this statement comes from "switch radio button" that you can rotate to select a channel. We use a "switch" statement to split a logical path into multi-path workflow.The criteria for switching is a numeric variable that may take diferent values.For each value we create one "case". When value match with case selector then we execute the block.

switch

Switch Diagram

Example:

In this example for each day number from 0 to 6 we get the day name in English.

/* determine current day*/
function get_day(day) {
  let result = "";
  switch (day) {
    case 1:
        result = "Monday";
        break;
    case 2:
        result = "Tuesday";
        break;
    case 3:
        result = "Wednesday";
        break;
    case 4:
        result = "Thursday";
        break;
    case 5:
        result = "Friday";
        break;
    case 6:
        result = "Saturday";
        break;
    default:
        result = "maybe is Sunday";
  }
  return result;
}
var today = new Date();
console.log(get_day(today.getDay()));

Notes:

In this example we detect a workday from a weekend day. The cases are executed top down if a break do not exist. In all cases 1,2,3,4,5 we have workday in cases 0 or 7 we have WeekDay. This technique is called fall through.

/* determine if is weekend */
function get_day(day) {
    var result = "";
    switch (day) {
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
            result = "WorkDay";
            break;
        case 0:
        case 6:
            result = "Weekend";
            break;
        default:
            result = "Error";
    }
    return result;
}
var today = new Date();
console.log(get_day(today.getDay()));

Iterative Statements

Iterative statements are blocks of code executed multiple times in a loop. The number of iterations can be controlled by a control variable. An iterative block can be interrupted using "break" and we can create shortcuts using "continue" keywords.
loop

For/Loop Repetition

Note: In JavaScript we have five repetitive statements:

For loop

Execute a block of code for a specific number of times. This loop is controlled by an integer variable that is local to the block. In next example "i" play the role of control variable.Initial value is 0 and maximum limit is 5. When i == 5 the repetition will end.After the loop, control variable is out of scope.

Example:

//initial statement
var text = "" 
for (var i = 0; i < 10; i++) {
    //first block
    text = "i = " + i; 
    if (i == 5) {
        console.log("break")
        break
    }
    //second block
    if (i > 3) {
        console.log("continue")    
        continue
    }
    //third block
    console.log(text)
}
//next statement
console.log("final i=" + i);

For statement has 3 parts:

Control Variable:

Example:

By using let to declare the control variable we can not access it out of the loop.
for (let i = 0; i < 5; i++) {
   text = "i = " + i;
   console.log(text)
}
console.log(i); // error: i is not defined

For...in loop

This statement uses a visitor: x that enumerate members of an object. In next example we scan properties of a person object using "for in" loop and display each value.

Example:

var person = {first_name:"John", last_name:"Doe", age:25};
let text = "";
for (let x in person) {
   console.log(x);
   text += person[x]+" ";
}
console.log(text);

Note: In this example we use in operator to iterate over an object person. The "text" variable starts empty and accumulate data from person attributes. Notice x is not a number but instead a string that have values: first_name, last_name or age. To get the value we use person[x].

For... of loop

To iterate over values of an array you can use "for…of" loop. This is a bit different than "for…in" and you have to understand both before use them with array object. Notice an array in JavaScript is also an object so you can use both these statements with different results:

Example:

/* array traversal */
var array = [4,5,6];
// read keys: '0', '1', '2'
for (element in array) {
   console.log(element);
}
console.log(typeof(element)) // 'string'
// read values: 4, 5, 6
for (element of array) {
   console.log(element);
}
console.log(typeof(element)) // 'number'

Notice: The difference is:

Repetitive Statements

Repetitive statements are blocks similar to iteration. The difference is that the number of repetitions can be controlled by a condition. A repetitive statement can be interrupted using "break" and we can create shortcuts using "continue" keywords like for iterative statement.

While loop

It is a repetitive statement that execute as long as one condition is true. When the condition becomes false the statement will stop and control is given to next statement. If the condition is false in the first place, the loop will never execute.

loop

Repetition Diagram

Example:

let i = 2;
while (i < 10) {
   console.log("i = " + i);
   i++;
}
console.log(i); // 10

Notes:


Do while

This is a repetitive statement that execute at least once. It is controlled by a condition that evaluate only after first execution. When the condition becomes false, the repetition stop and control is given to the next statement.This statement is harder to understand so I have made a diagram for you.

do-while

do-while diagram

Example:

let i = 2;
do {
   console.log("i = " + i);
   i++;
} while (i < 10);

Notes:


Read next: Objects