Module 4 : Control Flow – Conditional Execution and Loops

Loops

After completing Module 4, the student will:

  • be able to force conditional execution of a group of statements (make decisions and branch the flow) using if-else and switch commands;

  • be able to force a group of statements to repeat in a loop using the for, while, and do-while commands, using both dependent and independent conditions on the number of iterations;

  • understand and be able to use loop-specific break and continue instructions;

  • be able to use the for-in statement to iterate over the properties of an object;

  • be able to use the for-of statement to walk through the elements of an array.

for … of

In addition to the regular for loop, there are two specific versions, one of which, for ... of, is dedicated for use with arrays.

It is performed exactly as many times as there are elements in the indicated array.

let values = [10, 30, 50, 100];
let sum = 0;
for (let i = 0; i < values.length; i++) {
    sum += values[i];
}
console.log(sum); // -> 190
let values = [10, 30, 50, 100];
let sum = 0;
for (let number of values) {
    sum += number;
}
console.log(sum); // -> 190

for … in

Enables us to walk through object fields.

If we want to retrieve the values stored in the fields, we use bracket notation.

let user = {
    name: "Calvin",
    surname: "Hart",
    age: 66,
    email: "CalvinMHart@teleworm.us"
};

for (let key in user) {
    console.log(key); // -> name, surname, age, email
    console.log(user[key]); // -> Calvin, Hart, 66, CalvinMHart@teleworm.us
};