Question presented to candidate: "If you call array.flat() with no arguments on a deeply nested array, how deep does it actually flatten? And is array.flatMap(fn) exactly the same as array.map(fn).flat(), or is there a real difference?"
What a strong answer should cover:
- 📌 Interview term:
flat(depth)— returns a new array with sub-array elements concatenated up to the specifieddepth— the default depth is exactly 1, verified directly: a triple-nested array called with no arguments genuinely only flattens ONE level, leaving a deeper sub-array intact. - 📌 Interview term:
flat(Infinity)— verified directly: passingInfinityas the depth genuinely flattens arbitrarily deep nesting completely, regardless of how many levels exist. - 📌 Interview term: the real, direct answer to the prompt's flatMap question — verified directly:
arr.flatMap(fn)andarr.map(fn).flat()genuinely produce the identical result for the same input — the real, practical difference is thatflatMapdoes it in a single pass, slightly more efficient than creating an intermediate mapped array first. - 📌 Interview term: flatMap only flattens ONE level, always — verified directly: even when the mapped callback's return value is nested TWO levels deep,
flatMapgenuinely only flattens the first level, leaving the deeper nesting intact — unlikeflat(), its depth is not configurable at all. - A precise answer names that
flat()genuinely removes sparse array holes as a side effect of flattening — verified directly — a real, secondary behavior beyond just concatenating nested arrays.
Clarifying questions expected:
- None — this is a definitional/comparison question; directly answering the prompt's default-depth and flatMap-equivalence questions with real proof is the strong signal.
Code / implementation expected: Yes — the direct depth comparisons (default, explicit depth, Infinity) plus the flatMap-vs-map-then-flat side-by-side are the clearest, most convincing demonstrations.