JS Loops and Iteration

Download (.odt) Download (Markdown)

While loops

[hook]

Regular while loop

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

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.

Number of iterations: 1

Output: 10

For loops

[hook]

Regular for loop

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

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.

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

Output:

username: John Mastodon

age: 21

country: Germany

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.

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).

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).

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.

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