Skip to content

Instantly share code, notes, and snippets.

@elishaking
Created February 15, 2020 11:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elishaking/d20c24d6085c17d23693ac4a333b9f6a to your computer and use it in GitHub Desktop.
Save elishaking/d20c24d6085c17d23693ac4a333b9f6a to your computer and use it in GitHub Desktop.
Iterations

Iterations

Iteration involves the repetition of a block of code several times until a desired task is complete.

In JavaScript, there are three main tools that can be used for iterations:

For Loop

The for loop is the best tool to use when the number of repetitions is known. If an operation needs to be performed on every element in an array of length N, it becomes clear that N operations are needed and the for loop can be used to accomplish this

const arr = [1, 2, 3];
for (let i = 0; i < arr.length; i++) {
  arr[i] += 10;
}

While Loop

When the number of repetitions needed is unknown, then the while loop is the recommended tool. To find the number of times a number can be divided by 2, the while loop is a good choice because the number of repetitions is unknown in this case

let n = 10,
  r = 0;
while (n % 2 === 0) {
  n /= 2;
  r++;
}

Do While Loop

The do while loop can be used when the operation to be repeated must be performed at least once.

let n = 10;
do {
  console.log(n);
  n--;
} while (n > 0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment