The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Use a loop to repeat a block of TypeScript without writing the same code again. Choose a counted for loop when you need an index or a fixed progression, for...of to process iterable values, for...in to inspect enumerable object keys, and while or do...while when a condition controls repetition.
Choose the loop that matches the job
| Need | Loop | What it gives you |
|---|---|---|
| Control a counter, index, or custom step | for |
Initialization, a continuation condition, and an afterthought in one statement. |
| Process values from an iterable | for...of |
Each value, without manual index management. |
| Process enumerable object property keys | for...in |
Property keys, not values. |
| Repeat while a condition is true; zero runs are possible | while |
The condition is checked before each pass. |
| Run the body once before deciding whether to repeat | do...while |
The condition is checked after each pass. |
These forms follow JavaScript iteration-statement semantics. The TypeScript handbook explains the distinction between iterable values and property keys in its Iterators and Generators documentation.
As an Amazon Associate I earn from qualifying purchases.
Repeat a fixed number of times with for
A counted loop is useful when the number of passes, an array index, or a deliberate progression matters:
for (let i = 0; i < 3; i++) {
console.log(`Run ${i + 1}`);
}
This prints “Run 1”, “Run 2”, and “Run 3”. The three parts of the loop run in this order:
#1 Best Overall
- Initialization:
let i = 0runs once, before the loop begins. - Condition:
i < 3is checked before each pass. If it is false, the body does not run. - Body: the statements inside the braces run when the condition is true.
- Afterthought:
i++runs after the body completes, then the condition is checked again.
For an array, use a strict upper bound when iterating by index:
const names = ["Ada", "Grace", "Linus"];
for (let i = 0; i < names.length; i++) {
console.log(names[i]);
}
Array indexes start at zero, so the final valid index is one less than names.length. Using i <= names.length can make the loop attempt to read one position beyond the array. The MDN reference for for documents the loop’s condition and increment behavior.
Process values with for...of
When you need each value and do not need to manage an index, for...of is usually the clearest array loop:
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Clear out junk files and repair common Windows errors3Scan for outdated or missing drivers - takes under a minuteRank #2
- TypeScript implements a superset of syntax for strictly typed development, facilitating deep static analysis and enhanced development environment integration. The compiler translates source into standard script formats, ensuring parity across any runtime.
- TypeScript is ideal for front-end developers, full-stack engineers, and software architects who build large-scale web applications. It serves those looking to improve code excellence, reduce bugs through static checking, and maintain complex projects more.
- Lightweight, Classic fit, Double-needle sleeve and bottom hem
const names = ["Ada", "Grace", "Linus"];
for (const name of names) {
console.log(name);
}
Each pass assigns the next value from the iterable to name. Use a counted for instead when the index or step is part of the task.
TypeScript’s output for for...of depends on the project’s target configuration and runtime assumptions. The TypeScript handbook describes native iterator output for ES2015 and newer targets and restrictions or array-specific lowering for ES5. Check the actual project configuration when iterating non-array values for older targets.
Use for...in for enumerable keys
for...in assigns enumerable property keys, so it is suited to inspecting an object’s keys rather than processing an array’s values:
const settings = { theme: "dark", compact: true };
for (const key in settings) {
console.log(key);
}
For arrays, for...in is not the normal value loop: it yields keys and may also expose custom enumerable properties. Prefer for...of for values, or a counted loop if you need indexes. See the MDN reference for for...in.
Free tools Windows power users keep installed
One-click scans. No signup required.
Repeat based on a condition with while or do...while
while: check before the body
A while loop can run zero times because it tests its condition before entering the body:
let remaining = 3;
while (remaining > 0) {
console.log(remaining);
remaining--;
}
The state used by the condition changes on every pass, so the loop eventually stops when remaining reaches zero.
do...while: run the body first
Use do...while when the body must run at least once before the condition is checked:
let attempts = 0;
do {
attempts++;
} while (attempts < 1);
The condition is checked after the closing brace. This means the body runs once even if the condition is false after that first pass. MDN’s references explain the behavior of while and do...while.
Quick wins for a faster PC:
Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Clear out junk files and repair common Windows errorsFree Scan →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Skip or stop iterations with continue and break
continueends the current pass and moves to the next one.breakexits the loop immediately.
In a counted for loop, continue still proceeds to the afterthought and then checks the condition again. Keep that behavior in mind if you add continue to a loop whose progress depends on an update inside the body: the skipped update may prevent the loop from advancing.
Best Value
for (let i = 0; i < 5; i++) {
if (i === 1) {
continue;
}
if (i === 3) {
break;
}
console.log(i);
}
This skips the pass where i is 1 and exits when i reaches 3. The MDN for reference covers how a counted loop proceeds after these control statements.
Avoid loops that never finish
A loop can continue indefinitely if its condition never becomes false and no reachable break exits it. Before running a condition-controlled loop, identify what changes the condition and confirm that every path—including paths containing continue—still allows progress toward the exit.
- In a counted loop, check that the afterthought moves the counter toward the stopping condition.
- In a
whileordo...whileloop, update the state that the condition depends on or provide a reachable exit. - For arrays, use
i < items.lengthrather thani <= items.lengthwhen counting from zero.
For more detail on iteration statements and their behavior, consult the MDN guide to loops and iteration.
Use let for a loop counter captured by a closure
A let initializer in a for loop creates a per-iteration binding. That distinction matters when a callback closes over the counter: callbacks created in different passes can retain the corresponding iteration’s value. A counter declared with var, or declared outside the loop and shared, does not provide those separate per-iteration bindings; callbacks can instead observe a later shared value. The TypeScript documentation describes the loop’s let behavior in its iteration documentation.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




