Curriculum
Concept 65 // Module 07: Collections, Iteration & Modules
for...of vs for...in
Module 07: Collections, Iteration & Modules•Concept 65 of 100• 5 min read
for...of vs for...in
`for...of` iterates over **iterable values** (arrays, strings, Maps, Sets, Generators) using the Iteration Protocol. `for...in` iterates over all **enumerable property keys** of an object and its prototype chain.
The Core Concept
Summary rule of thumb: Use `for...of` for collections, arrays, and iterables. Use `Object.keys()` or `Object.entries()` with `for...of` for plain objects. Almost never use `for...in` on arrays.
Syntax Reference
// for...of (Values of Iterables)
for (const value of iterable) { ... }
// for...in (Keys of Objects)
for (const key in object) { ... }Live Interactive Studio
`for...in` treats arrays as plain objects, iterating over string keys and extra attached properties.
JavaScript Editor
Loading...
Console Output
Waiting for output...
Key Code Patterns in Action
01
The Classic Array Trap with for...in
const colors = ["red", "green", "blue"];
colors.customProperty = "custom";
console.log("--- for...of ---");
for (const color of colors) {
console.log(color); // "red", "green", "blue" (Values!)
}
console.log("--- for...in ---");
for (const index in colors) {
console.log(index, typeof index);
// "0" string, "1" string, "2" string, "customProperty" string ⚠️
}`for...in` treats arrays as plain objects, iterating over string keys and extra attached properties.
02
Prototype Chain Traversal in for...in
const parent = { inherited: true };
const child = Object.create(parent);
child.own = "yes";
for (const key in child) {
console.log(key); // "own", AND "inherited"! ⚠️
}
// Guarding with Object.hasOwn:
for (const key in child) {
if (Object.hasOwn(child, key)) {
console.log("Own key only:", key); // "own"
}
}`for...in` traverses inherited prototype keys unless filtered with `Object.hasOwn()`.
03
1. Core Usage: for...of vs for...in
// Core syntax and usage for for...of vs for...in
const feature = 'for-of-vs-for-in';
console.log('Concept 65:', feature);
console.log('Active:', true);Illustrates the fundamental invocation and syntax structure for for...of vs for...in.
04
2. Defensive Handling & Edge Case
// Edge-case defensive handling
function handleSafe(input) {
if (input === null || input === undefined) return 'safe-fallback';
return String(input).trim();
}
console.log(handleSafe('for-of-vs-for-in'));
console.log(handleSafe(null));Shows how to write defensive, safe JavaScript code that handles nullish or unexpected inputs when working with for...of vs for...in.
05
3. Clean Architecture & Production Pattern
// Production-grade pattern for for...of vs for...in
const settings = Object.freeze({
id: 'for-of-vs-for-in',
ready: true,
timestamp: Date.now()
});
console.log('Settings initialized:', settings.id, settings.ready);Demonstrates clean, immutable production code avoiding unintended state mutations.
Real-World Engineering Takeaways
Iterable Processing: Consuming strings character by character or reading array values with `for...of`.
Async Streams: Consuming async generators with `for await (const chunk of stream)`.
Property Auditing: Inspecting object keys and legacy property configurations.
Under the Hood: Engine & Memory Mechanics
How JavaScript Executes This
`for...of` calls the internal `[Symbol.iterator]()` method and repeatedly calls `.next()`. `for...in` requests the Shape/Map descriptor chain from the engine.
Quick Knowledge Check
Test your understanding on these 10 questions (one by one):
Score: 0 / 10
Question 1 of 10 • Core Purpose & Mental Model
What is the core purpose of for...of vs for...in in JavaScript?
// Concept 65: for...of vs for...in
// Understanding the core mental model1 / 10