The In Operator Checks Keys Not Values

in tests key existence across the prototype chain: sparse array holes fail, keys holding undefined pass, and Object.hasOwn limits the check to own properties.

JavascriptData Integrity

Code

javascriptsnippet
15 lines
// `in` asks "does this key exist?", never "is this value non-null?"
const settings = { retries: 0, label: undefined };
console.log('retries' in settings);  // true - the key exists with value 0
console.log('label' in settings);    // true - present even though the value is undefined
console.log('timeout' in settings);  // false - really missing

// On arrays the keys are indices: holes are false, defined slots are true
const sparse = ['a', , 'c'];         // index 1 is a hole
console.log(0 in sparse, 1 in sparse, 2 in sparse); // true false true
console.log(sparse[1] === undefined); // reading the hole also yields undefined

// `in` walks the prototype chain; Object.hasOwn stops at own properties
console.log('toString' in settings);              // true - inherited
console.log(Object.hasOwn(settings, 'toString')); // false - not an own property
console.log('length' in sparse);                  // true - length is an array property

Output

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

true
true
false
true false true
true
true
false
true

What the demo checks

in tests key existence, not value truthiness: retries with value 0 prints true, label whose value is undefined prints true, and only the truly missing timeout prints false. On the sparse array, index 1 is a hole, so 1 in sparse prints false even though reading it yields undefined.

Prototype members are found too: toString in settings is true via the chain, while Object.hasOwn(settings, “toString”) stops at own properties and prints false. length in sparse is true because length is an own array property.

Practical notes

  • A hole and an undefined value both read as undefined; only in distinguishes them.
  • hasOwn is the strict check; in is the chain-walking check.

Interactive Tools for This Topic

FAQ

Does in see holes in sparse arrays?
No; a hole is a missing key, so 1 in sparse prints false. A slot holding undefined still prints true because the key exists.