When working in JavaScript, it is inevitable that you will encounter arrays (a type of data structure). Arrays are made up of multiple elements, and often we want to perform the same action on every element in an array. While we could write out this repeated action for every element in an array, this would be incredibly tedious for arrays with lots of elements. It would also go against the software development principe of DRY (“Don't Repeat Yourself”) code.
Good thing there is a better, more scalable way! That’s where loops come into play. With a loop, the repeated action only needs to be written once and it will execute on every item in the collection.
There are a few different loop options (depending on the situation). Below are the three main loop types:
- for loop
- forEach loop
- for ... of loop
for loop
The for loop is the most basic of the three loop types, and takes 3 expressions:
- Initialization: Typically used to initialize a counter variable.
- Condition: An expression evaluated before each pass through the loop. Whether the expression evaluates true or false determines what happens next: the statements in the loop body execute, or the loop exits.
- Iteration: An expression executed at the end of each iteration. This often involves incrementing or decrementing a counter.
The for loop should be used when the number of times the loop should run is known.
const menuItems = ["hamburger", "pizza", "salad", "sandwich"]
for (let i = 0; i < menuItems.length; i++) {
console.log(`I ordered a ${menuItems[i]}`)
}
//RETURN
// I ordered a hamburger
// I ordered a pizza
// I ordered a salad
// I ordered a sandwich
In the example above, we set the variable “i” equal to zero. We declare the variable “i” using “let” (as opposed to “const”) because we need to increase the value of “i.” The value of “i” is increased by 1 each time the loop runs. When the value of “i” is less than the length of the menuItems array (4), the code in the code body runs.
forEach loop
In contrast with the for loop, the forEach and for ... of loops were designed to iterate (rather than loop) over elements within an array. While looping executes a set of statements until a condition is met, iteration executes code once for each item in a collection (often elements in an array).
const menuItems = ["hamburger", "pizza", "salad", "sandwich"]
menuItems.forEach(item => console.log(`I ordered a ${item}`));
//RETURN
// I ordered a hamburger
// I ordered a pizza
// I ordered a salad
// I ordered a sandwich
You will see in the example above that there is no initialization of a counter, no condition, no incrementing the counter, and no bracket notation to access elements inside the menuItems array. So while for loops can be used to iterate over each element in an array, using a forEach (or for … of) loop results in cleaner, readable code.
for ... of loop
The forEach and for ... of loops are similar to one another, as they both work to iterate over elements in an array.
One important distinction relates to control flow; the order in which a computer executes statements in a script. The for ... of loop supports normal control flow statements (like break and continue), while the forEach loop does not.
- Break: "jumps out" of a loop
- Continue: "jumps over" one iteration in the loop
const menuItems = ["hamburger", "pizza", "salad", "sandwich"]
for (const item of menuItems) {
console.log(`I ordered a ${item}`);
}
//Return:
// I ordered a hamburger
// I ordered a pizza
// I ordered a salad
// I ordered a sandwich
Conclusion:
When you first start working with JavaScript, it may initially seem like there are so many different options when it comes to looping and iterating. However, with a little practice, you too will grasp when one method should be used vs. another.
References:
"Loops and iteration." MDN Web Docs, developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration. Accessed 4 Apr. 2023.
Salvadó, Christian C. Comment on "Loop through an array in JavaScript." Stack Overflow, 10 June 2010, stackoverflow.com/questions/3010840/loop-through-an-array-in-javascript. Accessed 4 Apr. 2023.
"JavaScript Break and Continue." W3Schools, www.w3schools.com/js/js_break.asp. Accessed 4 Apr. 2023.
"Looping Lab." Canvas - Flatiron School, Accessed 4 Apr. 2023.
"Object Iteration." Canvas - Flatiron School, Accessed 4 Apr. 2023.
Top comments (0)