Home >Web Front-end >JS Tutorial >Understanding Object Iteration in JavaScript: `for...of` vs `for...in`
Iterating over objects is a common task in JavaScript, but knowing the correct technique for each situation can make your code cleaner and more efficient. This article explains why you can't use for...of directly with objects, offers alternative approaches, and provides best practices for iterating over objects.
In JavaScript, iterating over data structures is an essential part of handling complex datasets. While arrays and strings are iterable objects, plain objects (key-value pairs) require different methods for iteration. When developers try to use for...of on objects, they often encounter issues.
The for...of loop is used to iterate over iterable objects like arrays, strings, Maps, and Sets. Plain JavaScript objects, however, are not iterable by default.
const user = { name: 'John', age: 30 }; for (const value of user) { console.log(value); } // TypeError: user is not iterable
Attempting to use for...of on a plain object throws a TypeError. This happens because objects in JavaScript do not have a [Symbol.iterator] method, which is required for the for...of loop.
To iterate over objects in JavaScript, several techniques are available:
The for...in loop iterates over an object’s enumerable properties. It loops through the keys of the object.
const user = { name: 'John', age: 30 }; for (const key in user) { console.log(key, user[key]); } // Output: // name John // age 30
Object.keys() returns an array of the object’s own property keys, allowing you to use for...of to iterate over them.
const user = { name: 'John', age: 30 }; for (const key of Object.keys(user)) { console.log(key, user[key]); } // Output: // name John // age 30
Object.values() returns an array of the object’s property values, which can then be iterated over with for...of.
const user = { name: 'John', age: 30 }; for (const value of Object.values(user)) { console.log(value); } // Output: // John // 30
Object.entries() returns an array of the object’s key-value pairs, which makes it perfect for iterating over both keys and values.
const user = { name: 'John', age: 30 }; for (const [key, value] of Object.entries(user)) { console.log(key, value); } // Output: // name John // age 30
|
Access to Keys | Access to Values | Inherited Properties | Simplicity | |||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
for...in | Yes | Yes | Yes (if enumerable) | Simple | |||||||||||||||||||||||||
Object.keys() for...of | Yes | No | No | Moderate | |||||||||||||||||||||||||
Object.values() for...of | No | Yes | No | Moderate | |||||||||||||||||||||||||
Object.entries() for...of | Yes | Yes | No | Slightly complex |
The for...in loop is used to iterate over the enumerable properties (keys) of an object, including properties that may be inherited through the prototype chain.
const user = { name: 'John', age: 30 }; for (const key in user) { console.log(key, user[key]); } // Output: // name John // age 30
const colors = ['red', 'green', 'blue']; for (const index in colors) { console.log(index, colors[index]); } // Output: // 0 red // 1 green // 2 blue
The for...of loop is used to iterate over iterable objects like arrays, strings, maps, sets, and other iterables. It loops over the values of the iterable.
const colors = ['red', 'green', 'blue']; for (const color of colors) { console.log(color); } // Output: // red // green // blue
const name = 'John'; for (const char of name) { console.log(char); } // Output: // J // o // h // n
Feature | for...in | for...of |
---|---|---|
Purpose | Iterates over object keys (including inherited properties) | Iterates over iterable values (arrays, strings, etc.) |
Works with Objects | Yes | No (objects are not iterable) |
Works with Arrays | Yes, but not ideal (returns indices) | Yes, ideal (returns values) |
Use Case | Best for iterating over object properties | Best for arrays, strings, maps, sets, etc. |
Sometimes, objects are nested, and you need to iterate through all levels of the object. Here's an example that uses recursion to handle nested objects.
const user = { name: 'John', age: 30, address: { city: 'New York', zip: 10001 } }; // Recursively iterate through the object function iterate(obj) { for (const [key, value] of Object.entries(obj)) { if (typeof value === 'object' && !Array.isArray(value)) { console.log(`Entering nested object: ${key}`); iterate(value); // Recursively call for nested objects } else { console.log(key, value); // Output key-value pair } } } iterate(user); // Output: // name John // age 30 // Entering nested object: address // city New York // zip 10001
The above is the detailed content of Understanding Object Iteration in JavaScript: `for...of` vs `for...in`. For more information, please follow other related articles on the PHP Chinese website!