3 min read
•Question 26 of 50easyWhat is the difference between for...of and for...in?
Understanding iteration methods in JavaScript.
What You'll Learn
- When to use each loop
- Key differences
- Common pitfalls
Comparison
| Feature | for...in | for...of |
|---|---|---|
| Iterates over | Keys/indices | Values |
| Works on | Objects, Arrays | Iterables only |
| Order | Not guaranteed | Guaranteed |
for...in (Keys)
code.jsJavaScript
// Objects
const obj = { a: 1, b: 2, c: 3 };
for (const key in obj) {
console.log(key); // 'a', 'b', 'c'
}
// Arrays (not recommended)
const arr = ['x', 'y', 'z'];
for (const index in arr) {
console.log(index); // '0', '1', '2' (strings!)
}for...of (Values)
code.jsJavaScript
// Arrays
const arr = ['x', 'y', 'z'];
for (const value of arr) {
console.log(value); // 'x', 'y', 'z'
}
// Strings
for (const char of 'hello') {
console.log(char); // 'h', 'e', 'l', 'l', 'o'
}
// Maps
const map = new Map([['a', 1], ['b', 2]]);
for (const [key, value] of map) {
console.log(key, value);
}Best Practice
code.jsJavaScript
// For arrays: use for...of
for (const item of array) { }
// For objects: use for...in with hasOwnProperty
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
console.log(key, obj[key]);
}
}
// Or use Object.entries
for (const [key, value] of Object.entries(obj)) {
console.log(key, value);
}