JS Loop For In
for…in iterates the keys of an object. It's right for plain objects — but the wrong tool for arrays.
Usage
JS
const user = { name: "Ada", age: 36, role: "admin" };
for (const key in user) {
console.log(key, user[key]);
}
// name Ada
// age 36
// role admin
Why NOT to use it on arrays
JS
const arr = ["a", "b", "c"];
Array.prototype.last = function () { return this[this.length - 1]; };
for (const i in arr) console.log(i);
// "0", "1", "2", "last" ← includes inherited prop, keys are strings, no order guarantee
When to use what
| You want… | Use |
|---|---|
| Object property names (own + inherited) | for…in |
| Object property names (own only) | Object.keys(obj) + for…of |
| Object [key, value] pairs | Object.entries(obj) |
| Array items | for…of or array methods |
| Array item + index | arr.forEach((v, i) => …) or for…of + entries() |
Skip inherited keys
JS
for (const key in obj) {
if (!Object.hasOwn(obj, key)) continue;
// ... safe to use obj[key]
}
Tip: In modern code, prefer
Object.entries(obj) with for…of. You get keys, values, and own-only — no hasOwn dance.Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from JS Loop For In!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Iterate the keys of an object.
for (const key
user) console.log(key);
Two letters.
Discussion
Loading…