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.

JavaScript6 min readConcept 10 of 62

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

const arr = ["🍎", "🍌", "🍇"];
// The loop execution sequence
for(let i = 0;i < arr.length;i++) {
console.log(arr[i]);
}
State: i = 0
Console Output
(Awaiting execution...)
iNotice how the initializer only runs once. Then the loop alternates between checking the condition, running the body, and executing the afterthought.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1Which loop is specifically designed to iterate over the keys (property names) of an object?
  2. 2What happens if you use a `for...in` loop on an array?
  3. 3In a standard `for (let i = 0; i < 5; i++)` loop, when does `i++` run?

Remember this

  • A standard for loop has three parts: initializer, condition, and afterthought.
  • Use for...of to iterate over the values of an Array or String.
  • Use for...in to iterate over the keys of an Object.
  • break exits the loop entirely; continue skips to the next iteration.

Done with this concept?

Mark it complete to track your progress. No login needed.