Suggest an editImprove this articleRefine the answer for “for...in VS for...of in an array”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)**`for...in`** iterates over an object's keys (indexes or property names) and is meant for objects, while **`for...of`** iterates over the values of an iterable object's elements and is meant for arrays, strings, Set, Map, and so on. **Key point:** on an array, `for...in` returns string indexes and picks up any manually added properties, while `for...of` visits only the array's actual elements in order.Shown above the full answer for quick recall.Answer (EN)ImageThe 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**)For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.