-
Notifications
You must be signed in to change notification settings - Fork 0
For Each Loops : JS
For loops are great for iterating over data structures.
Contains three expressions separated by ; inside the parentheses (``):
-
an initialisation starts the loop and can also be used to declare the iterator variable
var i = 0. -
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.
-
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]);
}
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]);
}
}
};
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.'.