Loops

The for Statement

This YouTube video was created by Steve Griffith.

This Scrimba screencast was created by Dylan C. Israel.

The for statement creates a loop that consists of three expressions separated by semi-colons and enclosed in parentheses. The three expressions are as follows:

  1. The initialization of the iterator
  2. The condition that is check before each loop to see if the loop should continue
  3. The iteration of the iterator

The body of the for statement is enclosed in a set of curly braces ({}) and is executed each the statement loops as long as the condition evaluates to true.

for (let i = 1; i <= 10; i++) {
  console.log(10) // Logs 1 to 10
}

The for statement can also be used to iterate over arrays by using the iterator as the array index.

const animals = ['cat', 'dog', 'mouse']

for (let i = 0; i < animals.length; i++) {
  // Logs all the animals in the array
  console.log(animals[i]) 
}

The for...of Loop

This YouTube video was created by Steve Griffith.

This Scrimba screencast was created by Dylan C. Israel.

The for...of Loop is a fairly new loop which is specifically designed to iterate over arrays. Unlike the for statement, which accesses the each item of an array by its index, the for...of loop stores the value of each item to a defined variable.

The expression of the for...of loop starts with a initialization of the variable that will be used to hold the value of each item. This is followed by the keyword of and ends with the array.

Note

The for...of loop does NOT work with objects.

const animals = ['cat', 'dog', 'mouse']

for (const animal of animals) {
  // Logs all the animals in the array
  console.log(animal) 
}

The for...in Loop

This YouTube video was created by Steve Griffith.

The for...in Loop is similar to the for...of loop with a couple of exceptions. First, the for...in loop is designed to work with objects and second the variable will equal the key or index not the value.

The expression of the for...in loop starts with a initialization of the variable that will be used to hold the key of each item. This is followed by the keyword in and ends with the object or array.

Note

The for...in loop does not return items in a specific order, so it is not advised to use it with arrays.

const sounds = {
  cow: 'moo',
  duck: 'quack',
  horse: 'nay'
}

for (const animal in sounds) {
  // Logs each animals' sound
  console.log(sounds[animal]) 
}

The while and do while Loops

This YouTube video was created by Steve Griffith.

This Scrimba screencast was created by Dylan C. Israel.