JS Built-ins
← Array101 / 226
ArrayArray.prototype.forEachintermediate

Array.prototype.forEach() β€” implement map manually

πŸ“– Usage Example
const nums = [1, 2, 3]
// forEach β€” side effects only
nums.forEach(n => console.log(n))
// map β€” returns new array
nums.map(n => n * 2)  // β†’ [2, 4, 6]

Choose forEach() for side effects and map() when you need a transformed array.

Array.prototype.forEach() β€” manual map

You can implement map manually using forEach by pushing each mapped result into an external array. This illustrates the difference: map builds a new array automatically; forEach requires you to do it manually.

Challenge: Implement mapWithForEach(arr, fn) that applies fn to each element and returns a new array β€” using forEach instead of map.

mapWithForEach([1, 2, 3], n => n * 2) // β†’ [2, 4, 6]
πŸ’‘ Hints (2)
  • β€’ Create an empty result array, then `push(fn(n))` for each element.
  • β€’ This is exactly what `map` does internally β€” but `map` is more concise and idiomatic.