Module 4

Loops

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
};