JavaScript: Iteration Flashcards
Why is a “for loop” used?
We use a for
loop to execute code more than once.
What are the three parts of a “for loop?”
What is the syntax?
- declare counter (index)
- declare expression saying how long the loop will run (end condition)
- How to increment or decrement your counter variable
for (let i = 0; i <= 1; i++) {
console.log(‘This is the current value of i: ${i}.`);
}
Note: i++ is shorthand for i + 1
How would you use a “for loop” to create a numbered list of all data in the array?
What is the syntax?
const zooAnimals = [“Bears”, “Giraffes”, “Penguins”, “Meerkats”];
…
for (let i = 0; i < zooAnimals.length; i++) {
console.log( ‘${i + 1}) ${zooAnimals[i]}`);
}
How would you use a “for loop” to create a list of all data in the array (without index numbers)?
What is the syntax?
const zooAnimals = [“Bears”, “Giraffes”, “Penguins”, “Meerkats”];
…
for (const animal of zooAnimals) {
console.log(animal);
}