For In Enumerates Keys While For Of Reads Values

for...in walks string keys including enumerable extras, for...of reads elements through the iterator protocol, and plain objects need Object.entries for of.

JavascriptConfig Management

Code

javascriptsnippet
30 lines
// for...in 走字符串键(含可枚举继承键),for...of 走值(需可迭代对象)
const flags = { retry: true, verbose: false };
Object.defineProperty(flags, 'internal', { value: 1, enumerable: false });
console.log('for...in keys:', Object.keys(flags).join(','));

const ownKeys = [];
for (const key in flags) {
  ownKeys.push(key);
}
console.log('enumerable keys visited:', ownKeys.join(','));

// 数组也是对象:for...in 给出的是索引字符串,还可能带上自定义属性
const items = ['a', 'b'];
items.last = 'sentinel';
const seen = [];
for (const key in items) {
  seen.push(key);
}
console.log('array for...in:', seen.join(','), '(index strings plus custom props)');

// for...of 遍历元素本身;数组内置 [Symbol.iterator]
const values = [];
for (const item of items.slice(0, 2)) {
  values.push(item);
}
console.log('for...of values:', values.join(','));

// 普通 object 不是 iterable:要按对遍历就转成 Object.entries
const pairs = Object.entries(flags).filter(([, v]) => v === true);
console.log('entries filter:', pairs.map(([k]) => k).join(','));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

for...in keys: retry,verbose
enumerable keys visited: retry,verbose
array for...in: 0,1,last (index strings plus custom props)
for...of values: a,b
entries filter: retry

How it works

The core work runs in nested loops — outer for (const key in flags), inner for (const key in items).

Module-level bindings hold the data — flags, ownKeys, items, seen — with no function scope in between.

The top-level object literal pins retry, verbose as plain values — no derivation, no imports behind them.

What to watch for

  • Zero-fetch snippet: every identifier resolves inside the language distribution.

Putting it to use

Each run prints the 5 labeled blocks for...in keys:, enumerable keys visited:, array for...in:, for...of values:, entries filter: in source order.

Core lines

const pairs = Object.entries(flags).filter(([, v]) => v === true);

Interactive Tools for This Topic

FAQ

Is the dependency story complicated?
Not at all: zero dependencies, so there is nothing to version or audit. Its state lives in module-level bindings: `flags`, `ownKeys`, `items`.