When should I choose `for...of` instead of `for...in`?
Quick answer
for...of is usually the right choice when you want to process an array’s values. for...in gives you enumerable property names, which for an array are index names and can include user-added properties. [S1] Choose based on whether your loop needs each value or each property key; the two loops do not produce the same kind of result.
The question, the details, the next step.
A practical checklist
Name what the loop body needs: an item value or a property key.
For array values, choose
for...ofand use a value-named loop variable.For property names, choose
for...inand name the variablekeyorproperty.Check whether an array may have extra enumerable properties before using
for...in.Run a tiny example and inspect the loop output if you are unsure what the variable contains.
A few more useful answers
Does `for...in` give me numbers for array indexes?
It gives enumerable property names, including array index names; in the example they appear as 0 and 1, not as the array’s values. [S1]
Can I use `for...of` on something other than an array?
Yes, when the value supplies an iterable. for...of iterates values from an iterable; this guide’s examples focus on arrays. [S1]
Which loop should I use to get both an array index and its value?
Neither loop variable automatically gives you both in the examples shown: for...of gives values, while for...in gives property names. Choose based on what your task needs, and consult JavaScript documentation for an approach that provides both.
Sources
References used for this guide.
- [S1] Loops and iteration — JavaScript | MDN developer.mozilla.org · Checked
