JS Built-ins
← Array146 / 226
ArrayArray.prototype.pushintermediate

Array.prototype.push() β€” collect evens with forEach

πŸ“– Usage Example
const evens = []
[1,2,3,4,5].forEach(n => { if (n%2===0) evens.push(n) })
evens  // β†’ [2, 4]

Use push() to collect matching elements into a result array during iteration.

Collecting values with push

A common pattern: use forEach to iterate and push to collect matching elements into a new array.

const evens: number[] = []
[1, 2, 3, 4].forEach(n => { if (n % 2 === 0) evens.push(n) })
// evens === [2, 4]
πŸ’‘ Hints (3)
  • β€’ Use `n % 2 === 0` to check for even numbers.
  • β€’ Declare `const result: number[] = []` before the loop.
  • β€’ Call `result.push(n)` inside the `if` block.