Loops: for, while, for...of, for...in
How to repeat actions in JavaScript. Learn the standard loops and the modern variations for iterating over arrays and objects.
What are loops?
Loops are used to run the same block of code multiple times, usually with a slightly different value each time.
The most traditional loop is the for loop, which has three parts: an initializer (let i = 0), a condition (i < 5), and an afterthought (i++).
Why are there so many kinds?
Different data structures require different approaches to iterate over them cleanly.
A standard for or while loop is great when you just want to repeat something 'X' amount of times.
The for...of loop was introduced to easily grab the *values* out of an Array or String without dealing with index math.
The for...in loop is designed specifically to grab the *keys* (property names) out of an Object.
The syntax breakdown
for (let i = 0; i < 3; i++): The classic loop. Good for counting.
while (condition): Repeats as long as the condition is truthy. Make sure the condition eventually becomes false, or you will create an infinite loop that crashes the browser!
for (const value of array): The modern, clean way to loop over an array's contents.
for (const key in object): The way to loop over an object's properties.
The Loop Stepper
Step through a traditional for loop iteration by iteration to see exactly how the initializer, condition, body, and afterthought execute in order.
The Loop Stepper
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- A standard
forloop has three parts: initializer, condition, and afterthought. - Use
for...ofto iterate over the values of an Array or String. - Use
for...into iterate over the keys of an Object. breakexits the loop entirely;continueskips to the next iteration.
Done with this concept?
Mark it complete to track your progress. No login needed.