for...in VS for...of in an array
The difference between for...in and for...of in JavaScript is one of those things you need to understand clearly, especially when working with arrays.
In brief:
| Loop | What it iterates | Used for |
|---|---|---|
for...in | Keys / indexes (property names of an object) | objects |
for...of | Values of elements (from iterable objects) | arrays, strings, Set, Map, etc. |
Example 1 - array
javascript
const arr = ["a", "b", "c"];for...in iterates indexes (keys):
javascript
for (const index in arr) {
console.log(index); // "0", "1", "2"
}- Returns string indexes (not numbers!).
- Suited for objects, not arrays.
- May pick up extra properties, if added manually.
for...of iterates values:
javascript
for (const value of arr) {
console.log(value); // "a", "b", "c"
}- Works with iterable objects (Array, String, Set, Map...).
- Returns element values.
- Ideal for arrays.
Example 2 - the difference in practice:
javascript
const arr = ["x", "y", "z"];
arr.custom = "hello"; // add a property manually
for (const key in arr) {
console.log(key); // "0", "1", "2", "custom"
}
for (const value of arr) {
console.log(value); // "x", "y", "z"
}for...in walks through all enumerable properties of the object, including manually added ones.
for...of visits only the array's elements.
Example 3 - working with a string (an iterable object)
javascript
for (const char of "JS") {
console.log(char); // "J", "S"
}for...of works great with strings.
for...in on a string returns indexes "0", "1".
In short:
| Feature | for...in | for...of |
|---|---|---|
| Iterates | keys (indexes, properties) | values |
| Works with | objects, arrays | iterable objects (array, string, Set, Map) |
| Returns | strings, property names | actual values |
| Order | can be unpredictable | preserves order |
| Suited for arrays | No | Yes |
| Suited for objects | Yes | No |
Remember it simply:
for...in→ iterates keys (for objects)for...of→ iterates values (for arrays and iterable objects)
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.