JavaScript for...in

Beginner
5 min read
Updated: Nov 2026
3 examples

Definition and Usage

for...in walks the enumerable property names (keys) of an object, including inherited enumerable keys. Prefer Object.keys or for...of for arrays.

JavaScript Syntax

JavaScript
const user = { name: "Ada", age: 36 };
for (const key in user) {
  console.log(key + "=" + user[key]);
}
Try it Editor

How It Works

  1. Keys first. key is "name", then "age".
  2. Read values. Use user[key] with brackets.

Examples

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);
Try it Editor

How It Works

  1. Keys are string indexes.
  2. Use for...of for values.

Example 2 — Own keys only

Filter with hasOwn or Object.keys.

JavaScript
const o = { a: 1 };
for (const k of Object.keys(o)) console.log(k);
Try it Editor

How It Works

  1. Object.keys returns own enumerable keys.
  2. Safer for plain data objects.

Example 3 — Key order

Integer-like keys sort; others keep insertion order.

JavaScript
const o = { b: 1, a: 2 };
console.log(Object.keys(o).join(","));
Try it Editor

How It Works

  1. Non-integer keys keep insertion order in modern engines.

Frequently Asked Questions

for...in → keys. for...of → values of an iterable (arrays, strings, Maps).
Yes for enumerable inherited properties. Prefer Object.keys or hasOwn for own keys only.

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful