Skip to content

For Each Loops : JS

Marie-Louise edited this page Feb 1, 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]);
    }
  }
};

Break

The break keyword allows programs to “break” out of the loop from within the loop's block.

const rapperArray = ["Lil' Kim", "Jay-Z", "Notorious B.I.G.", "Tupac"];


for (let i = 0; i < rapperArray.length; i++){
  console.log(rapperArray[i]);
  if (rapperArray[i] === 'Notorious B.I.G.'){
    break;
  }
}

console.log("And if you don't know, now you know.");

the example above ... Logs each element from rapperArray in a for loop with the iterator variable i. a break inside your loop's block that breaks out of the loop if the element at the current index in the rapperArray is 'Notorious B.I.G.'.

Clone this wiki locally