flat, concat, reverse & More in JavaScript
Beyond the big five live the specialists: flat(depth) and flatMap flatten nesting (one level by default, Infinity for full), concat merges without mutating (spread usually reads better now), reverse sorts in place (copy first!), join stringifies with separators, and keys/values/entries yield iteration helpers.
ES2023 adds non-mutating trio toSorted/toReversed/with for immutable pipelines. Fill and copyWithin handle bulk initialization and shifting. The pattern across all: know which mutate (reverse, sort, splice) versus return fresh (map, filter, slice, flat).
flat flattens nesting
[1, [2, [3]]].flat(2) β [1, 2, 3] β depth-controlled, Infinity for arbitrary depth.
flatMap maps then flattens
One level of flattening fused with mapping β splitting sentences to words in a single pass.
reverse mutates
arr.reverse() flips in place β [...arr].reverse() or toReversed() when the original must survive.
Know mutating vs pure
Mutators: sort, reverse, splice, fill, copyWithin. Pure: map, filter, slice, flat, concat, toSorted.
let nested = [1, [2, 3]];console.log(nested.flat());let words = ["hi there", "yo"];console.log(words.flatMap((s) => s.split(" ")));Recommended resourcesAffiliate links Β· may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in JavaScript yourself β building beats watching.