Example 1 — Avoid for...in on arrays
Indexes come as strings; holes and inherited keys surprise you.
JavaScript
const a = ["x", "y"];
for (const i in a) console.log(i, typeof i); How It Works
- Keys are string indexes.
- Use for...of for values.
for...in walks the enumerable property names (keys) of an object, including inherited enumerable keys. Prefer Object.keys or for...of for arrays.
const user = { name: "Ada", age: 36 };
for (const key in user) {
console.log(key + "=" + user[key]);
} Indexes come as strings; holes and inherited keys surprise you.
const a = ["x", "y"];
for (const i in a) console.log(i, typeof i); Filter with hasOwn or Object.keys.
const o = { a: 1 };
for (const k of Object.keys(o)) console.log(k); Integer-like keys sort; others keep insertion order.
const o = { b: 1, a: 2 };
console.log(Object.keys(o).join(",")); CODETOFUN NEWS
Get the latest IT news, programming updates, and technology trends directly on your phone.
Your daily dose of tech, straight to your feed.
6 people found this page helpful