for vs for...of vs for...in

Three loop constructs in JavaScript. Each is designed for different iteration scenarios.

Featurefor loopfor...offor...in
Syntaxfor (let i = 0; i < n; i++)for (const item of iterable)for (const key in object)
Best forWhen you need the index, or non-standard iterationIterating array values, most general-purpose loopsIterating object keys (use Object.keys/entries instead)
Works onArrays, strings, any indexed structureArrays, strings, Maps, Sets, generatorsObjects (avoid on arrays)
Iterates overIndex-based (any countable range)Values of iterable objectsEnumerable property names (keys)
Can break/continueYesYesYes

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