for vs for...of vs for...in
Three loop constructs in JavaScript. Each is designed for different iteration scenarios.
| Feature | for loop | for...of | for...in |
|---|---|---|---|
| Syntax | for (let i = 0; i < n; i++) | for (const item of iterable) | for (const key in object) |
| Best for | When you need the index, or non-standard iteration | Iterating array values, most general-purpose loops | Iterating object keys (use Object.keys/entries instead) |
| Works on | Arrays, strings, any indexed structure | Arrays, strings, Maps, Sets, generators | Objects (avoid on arrays) |
| Iterates over | Index-based (any countable range) | Values of iterable objects | Enumerable property names (keys) |
| Can break/continue | Yes | Yes | Yes |
Verdict
Use for...of for arrays and iterables. Use Object.entries() or Object.keys() with for...of for objects. Use classic for loops when you need the index. Avoid for...in on arrays.
Code Example
Javascript
Tip: Modify the code above and click “Run” to see the results
Related Tutorials
Related Glossary Terms
Higher-Order Function
A function that either takes one or more functions as arguments, returns a function, or both. Common examples include map, filter, reduce, and forEach.
Array MethodsBuilt-in methods on the Array prototype for transforming and querying arrays. Key methods include map (transform each element), filter (select elements), reduce (accumulate), find (first match), some/every (boolean tests), and sort.