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

Array.prototype.forEach() β€” mutate array in-place

πŸ“– Usage Example
const log = []
[1, 2, 3].forEach(n => log.push(n * 2))
log  // β†’ [2, 4, 6]

Use forEach() when you need side effects like pushing to another array or calling an API.

Array.prototype.forEach() β€” index-based mutation

The forEach callback receives three arguments: (value, index, array). You can use the index to mutate elements in-place by writing back to array[index].

Challenge: Implement multiplyInPlace(arr, factor) that multiplies each element in the array by factor using forEach.

const arr = [1, 2, 3]
multiplyInPlace(arr, 2)
// arr is now [2, 4, 6]
πŸ’‘ Hints (2)
  • β€’ The third argument to the callback is the original array β€” use `array[index] = ...` to mutate it.
  • β€’ `forEach` returns `undefined` β€” it is only useful for its side effects.