Skip to content

For Each Loops : JS

Marie-Louise edited this page Jan 31, 2019 · 10 revisions

For loops are great for iterating over data structures.

Structure

Contains three expressions separated by ; inside the parentheses (``):

  1. an initialisation starts the loop and can also be used to declare the iterator variable var i = 0.

  2. a stopping condition is the condition that the iterator variable is evaluated against— if the condition evaluates to true the code block will run, and if it evaluates to false the code will stop.

  3. an iteration statement is used to update the iterator variable on each loop.

    for (let counter = 0; counter < 4; counter++) { console.log(counter); }

    for (let counter = 5; counter < 11; counter++) { console.log(counter); }

The loop below loops from 0 to 3. Edit it to loop backwards from 3 to 0

for (let counter = 3; counter >= 0; counter--){
  console.log(counter);
}

how to iterate through arrays

const animals = ['Grizzly Bear', 'Sloth', 'Sea Lion'];
for (let i = 0; i < animals.length; i++){
  console.log(animals[i]);
}

const vacationSpots = ['Bali', 'Paris', 'Tulum'];

for (let i = 0; i < vacationSpots.length; i++ ){
  console.log('I would love to visit ' + vacationSpots[i]);
}

Nested loops

if bobFollowers equals tinasFollowers, then push bobFollowers to the empty array mutualFollowers

let bobsFollowers = ['Joe', 'Marta', 'Sam', 'Erin'];
let tinasFollowers = ['Sam', 'Marta', 'Elle'];
let mutualFollowers = [];

for (let i = 0; i < bobsFollowers.length; i++) {
  for (let j = 0; j < tinasFollowers.length; j++) {
    if (bobsFollowers[i] === tinasFollowers[j]) {
      mutualFollowers.push(bobsFollowers[i]);
    }
  }
};

Clone this wiki locally