August 13, 2021
for…in vs for…of in JavaScript β Simple Explanation
β
What is for...in
?
for...in
loops over keys (property names) in an object or array.
π§ͺ Example:
const obj = { a: 1, b: 2, c: 3 };
for (let key in obj) {
console.log(key); // a, b, c
console.log(obj[key]); // 1, 2, 3
}
π§ͺ In arrays:
const arr = ['x', 'y', 'z'];
for (let index in arr) {
console.log(index); // 0, 1, 2
console.log(arr[index]); // x, y, z
}
π‘ Note: for...in
gives index, not values for arrays.
β
What is for...of
?
for...of
loops over values of iterable objects (like arrays, strings, maps, sets).
π§ͺ Example with array:
const arr = ['x', 'y', 'z'];
for (let value of arr) {
console.log(value); // x, y, z
}
π§ͺ Example with string:
for (let char of 'hello') {
console.log(char); // h, e, l, l, o
}
π’ for...of
is not for plain objects, unless you use Object.entries()
or similar.
βοΈ Comparison Table
Feature | for...in | for...of |
---|---|---|
Iterates over | Property keys (names) | Property values |
Works on objects | β Yes | β No (unless iterable) |
Works on arrays | β Yes (indexes) | β Yes (values) |
Output for array | Indexes: 0, 1, 2... | Values: 'a', 'b', 'c'... |
Use case | Loop through object keys | Loop through values of array, string, map, set |
π‘ When to Use
You want to⦠| Use |
---|---|
Loop over object properties | for...in |
Loop over array values | for...of |
Loop over string characters | for...of |
Loop over Map / Set values | for...of |
Loop over array indexes manually | for...in |
β οΈ Important Notes
for...in
can loop over inherited properties, so it’s best withhasOwnProperty()
: jsCopyEditfor (let key in obj) { if (obj.hasOwnProperty(key)) { // safe to use } }
for...of
only works on iterable objects.
β Summary
for...in
= loop over keys (property names)for...of
= loop over values
π§ One-line answer for interviews:
“
for...in
is for object keys,for...of
is for iterable values like arrays or strings.”
Comments are closed.