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.