Question presented to candidate: "If I add a custom property directly onto an array, like myArray.total = 100, and then loop over the array with for...in, what actually shows up in the loop? Would for...of behave the same way?"
What a strong answer should cover:
- 📌 Interview term:
for...of— iterates over the values of anything implementing the iterable protocol (arrays, strings, Maps, Sets, generators) — it works only on genuinely iterable things, and genuinely does NOT see non-index properties. - 📌 Interview term:
for...in— iterates over an object's enumerable property keys (as strings), including inherited enumerable properties from the prototype chain — it works on any object, not just iterables, and was never really designed for arrays specifically. - 📌 Interview term: the real, direct answer to the prompt — verified directly: adding
myArray.total = 100and then usingfor...ingenuinely includes"total"as one of the loop's keys, alongside the numeric index keys — a real, concrete bug source.for...of, verified directly on the identical array, genuinely does NOT include it at all — it only ever produces the array's real element values. - 📌 Interview term:
for...ofon a non-iterable throws — verified directly: usingfor...ofon a plain object (which does not implement the iterable protocol) genuinely throws a realTypeError, whilefor...inworks on it fine. - A precise answer names the standard, real guidance this leads to: use
for...offor arrays/iterables (to get real values, safely, without picking up stray properties), and reach forfor...inonly when inherited/enumerable KEYS on a plain object are specifically needed — withObject.keys()/Object.entries()as the more precise, own-properties-only alternative in most real cases.
Clarifying questions expected:
- None — this is a definitional/comparison question; directly answering the prompt's own custom-property scenario with real proof is the strong signal.
Code / implementation expected: Yes — reproducing the prompt's exact scenario (a custom array property leaking into for...in) is the clearest, most convincing demonstration.