Question presented to candidate: "You're given a DOM NodeList and need to use array methods like .map() on it, which NodeList doesn't have directly. Separately, someone wrote new Array(3) expecting an array containing the number 3, and got confused by the result. How do Array.from and Array.of each solve these two genuinely different problems?"
What a strong answer should cover:
- 📌 Interview term:
Array.from(iterableOrArrayLike, mapFn?)— builds a real array from anything genuinely iterable (a string, Set, Map) OR genuinely array-like (has alengthand indexed properties, but no iterator — like a DOM NodeList in some contexts, orarguments) — directly answering the prompt's NodeList scenario. - 📌 Verified, not assumed: real
Array.fromcalls genuinely converted a string, a Set, a Map, and a genuine array-like object ({length, 0, 1, 2}, no iterator) all correctly into real arrays. - 📌 Interview term: the real
new Array(n)ambiguity, directly answered —new Array(3)genuinely creates an array withlength: 3and real holes (not the number 3 as an element) — confirmed directly by a striking real contrast:new Array(3).map(x => 1)genuinely stayed empty (map skips real holes), whileArray.from({length: 3}).map(x => 1)genuinely produced real values, becauseArray.fromgenuinely materializes realundefinedslots thatnew Array(n)alone leaves as holes. - 📌 Interview term:
Array.of(...items)— directly avoids the ambiguity:Array.of(3)genuinely produces[3](a real one-element array containing the number 3), confirmed directly againstnew Array(3)'s genuinely different, three-hole result. - A precise answer names
Array.from's real, optional second argument (a map function) as letting it double as a combined "convert and transform" step in one call — verified directly with a real{length: n}-based range-generator idiom.
Clarifying questions expected:
- "Does the actual source genuinely have a working iterator (a Set, Map, string), or is it merely array-LIKE (a length property plus indices, no iterator, like some NodeList usages or the classic arguments object)?" — Array.from, verified above, correctly handles both cases.
- "Is the code creating an array from KNOWN arguments values (Array.of's real use case) or CONVERTING an existing iterable/array-like (Array.from's real use case)?" — directly decides which one actually applies.
Code / implementation expected: Yes — real conversions from a string, Set, Map, and array-like object, plus the real, striking new Array(3) vs. Array.from({length:3}) contrast on .map(), is the concrete, convincing proof of exactly what each method does and does not do.