JavaScript Loops: for, for...of, for...in and while
JavaScript has several loops, and picking the right one makes code clearer. In everyday code you will mostly use for...of for arrays and the classic counting for when you need an index.
The classic for loop
for (let i = 0; i < 3; i++) has three parts separated by semicolons: an initializer that runs once, a condition checked before each pass, and an update that runs after each pass. It is flexible: you can count down, step by two, or stop early. Declare the counter with let so it stays inside the loop.
for...of: values of an iterable
for (const lang of langs) gives you each value of an array, one at a time, without any index bookkeeping. It works on anything iterable: arrays, strings (character by character), Map, Set and more. Use const for the loop variable unless you reassign it inside the body.
for...in: keys of an object
for (const key in book) gives you the property names of an object as strings. Read the value with book[key]. Do not use for...in on arrays: it yields indexes as strings, can include inherited properties, and is easy to confuse with for...of. For objects, Object.entries() combined with for...of is a popular alternative, as you will see in the objects chapter.
Expected output
i is 0 i is 1 i is 2 JS SQL title = Maps of Memory year = 2024 first power of 3 over 50: 81
while and do...while
while (condition) repeats as long as the condition is truthy, which suits loops where you do not know the number of passes in advance. In the example it multiplies by 3 until the value passes 50. A do { } while (condition) loop runs the body once before checking, which guarantees at least one pass.
break and continue
break leaves the loop immediately; continue skips to the next pass. The for...of loop above uses continue to skip "Python". Both work in every loop type.
Common mistakes
- Using
for...inon an array when you meantfor...of. - Off-by-one conditions:
i <= arr.lengthreads one item past the end and getsundefined. - Infinite
whileloops because nothing in the body changes the condition.
Summary
- Classic
for (init; condition; update)for counting and indexes. for...offor values of arrays, strings, Maps and Sets.for...infor the keys of plain objects.whilewhen the number of passes is unknown;breakandcontinuecontrol flow.
Quiz: Loops