JS Loops and Iteration

Download (.odt) Download (Markdown)

While loops

[hook]

Regular while loop

Execute instruction(s) repeatedly until the specified condition is met.

let i = 1;
while (i <= 10) {
  console.log(i);
  i++; // increase counter by one at the end of each iteration
}

Number of iterations: 10

Output: 1 2 3 4 5 6 7 8 9 10

Do-while loop

Execute instruction(s) once no matter what, then repeat them until the specified condition is met.

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

Number of iterations: 1

Output: 10

For loops

[hook]

Regular for loop

Execute instruction(s) repeatedly until the specified condition is met.

let array = ["apple", "pineapple", "pen"];
for (let i = 0; i < array.length; i++) {
  console.log(list[i]);
}

Number of iterations: 3 (because object has 3 entries)

Output: apple pineapple pen

For-in loop

Iterate over an object and execute instruction(s) on it.

let object = {username: "John Mastodon", age: 21, country: "Germany"};
for (let property in object) {
  console.log(${property}: ${object[property]});
}

Number of iterations: 3 (because object has 3 entries)

Output:

username: John Mastodon

age: 21

country: Germany

let array = ["John Mastodon", "John Doe"];
for (let index in array) {
  console.log(${index}: ${array[index]});
}

Number of iterations: 2 (because array has 2 items)

Output:

0: John Mastodon

1: John Doe

Warning! For-in loop may not respect the order of items in array. If order matters, use regular for loop, for-of loop or forEach() method instead.

For-of loop

Iterate over an iterable data structure (array, string etc.) and execute instruction(s) on it.

let array = ["John Mastodon", "John Doe"];
for (let item of array) {
  console.log(item);
}

Number of iterations: 2 (because array has 2 items)

Output:

John Mastodon

John Doe

Statements for controlling loops

[hook]

Break

Quit the loop (often used with if statement).

let array = ["apple", "pineapple", "pen"];
let indexOfPineapple = -1;
for (let i = 0; i < array.length; i++) {
  if (array[i] === "pineapple") {
    indexOfPineapple = i;
    break;
  }
}

The index of the item "pineapple" is already found in second iteration (index 1) so it's redundant to keep the loop running. Quitting the loop using break is handy to reduce memory usage when running the code.

Or if there was multiple "pineapple" items in the array, you would get the last one after finishing loop. If you use break, you get the first one.

Continue

Jump to next iteration (often used with if statement).

let applicants = ["Linus Torvalds", "Bill Gates", "Richard Stallman", "Tim Cook"];
let rejected = ["Bill Gates", "Tim Cook"];
let guestlist = [];
for (let i = 0; i < applicants.length; i++) {
  if (rejected.includes(applicants[i])) {
    continue;
  }
  guestlist.push(applicants[i]);
}

Each iteration, the program checks whether the number i item of applicants array is on the rejectedApplicants array. If so, it skips remaining instructions (so in this case, the item won't be added to the guestlist array) and jumps to the next iteration.

So the guestlist will look like this: ["Linus Torvalds", "Richard Stallman"]

Array methods using iteration

[hook]

forEach()

Run a function on all items of an array.

let penPineapple = ["apple", "pineapple", "pen"];
penPineapple.forEach(function(item, index, array) {
  console.log(index, item);
});

Callback function can have 1-3 parameters (item, index, array), index and array are optional.

Output:

0 apple

1 pineapple

2 pen

Other methods

See Array Cheatsheet