In JavaScript, the for...of
loop is used to iterate over iterable objects. However, objects in JavaScript are not considered iterable by default. The for...of
loop is primarily used with arrays and other iterable data structures such as strings, maps, and sets.
If you want to iterate over the properties of an object, you can use the for...in
loop instead. The for...in
loop iterates over all enumerable properties of an object, including inherited ones. Here’s an example:
for (var key in test) {
var item = test[key];
}
For…of Object JavaScript example
If you want to iterate over the properties of an object, you can use the for...in
loop instead. The for...in
loop iterates over all enumerable properties of an object, including inherited ones. Here’s an example:
const obj = { a: 1, b: 2, c: 3 };
for (const key in obj) {
console.log(key, obj[key]);
}
If you specifically want to iterate over the values of an object, you can use Object.values()
to extract the values into an array, and then use the for...of
loop on that array.
const obj = { a: 1, b: 2, c: 3 };
const values = Object.values(obj);
for (const value of values) {
console.log(value);
}
Output:
Note: the order of iteration in JavaScript objects is not guaranteed. If you need a specific order, consider using an array or another data structure that preserves order.
Comment if you have any doubts or suggestions on this Js loop topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version