Different Iteration Targets and Purposes
Basic Concept Comparison
Category | for...in |
for...of |
---|---|---|
Iteration Target | Objects iterable by property (key or index) | Objects iterable by value |
Loop Behavior | Operates on properties (keys or indexes) retrieved from the object | Operates on values retrieved from the object |
Applicable Objects |
|
|
Usage | Used to iterate over the properties (keys) of an object | Used to iterate over the values of an object |
Purpose | Mainly for debugging, to check which properties (keys) exist in a plain object, rather than for handling data | Intended for handling data by iterating over values |
Examples
for...in
The for...in
loop is mainly used for debugging purposes, to check which properties (keys) exist in a plain object, rather than for handling data.
const user = {
name: "John",
age: 30
};
for (let key in user) {
console.log(key, ":", user[key]);
}
/*
Output:
"name" : "John"
"age" : 30
*/
for...of
<ul>
<li>Burger</li>
<li>Fries</li>
<li>Soda</li>
</ul>
const liElements = document.querySelectorAll("li"); // Select all li elements
console.log(liElements); // NodeList(3) [li, li, li]
// Applying for...of loop
for (const liElement of liElements) {
console.log(liElement.textContent);
}
// Output: "Burger" "Fries" "Soda"
Code Explanation
The NodeList
object returned by querySelectorAll()
is array-like and can be iterated using a for...of
loop.
Things to Keep in Mind
Specifications
Specification | |
---|---|
for...in, for...of
|
ECMAScript Language Specification #sec-for-in-and-for-of-statements |
Compatibility
Statement |
Desktop Chrome
|
DesktopDesktop Edge
|
Desktop Firefox
|
Safari
|
Node.js
|
---|---|---|---|---|---|
for...in
|
1 | 12 | 1 | 1 | 0.10 |
for...of
|
38 | 12 | 13 | 7 | 0.12 |