Array Iteration
👨💼 Often we need to process every element in an array. JavaScript provides
powerful methods for this.
Key iteration methods:
forEach(fn)- Run a function on each element (doesn't return anything)map(fn)- Transform each element, returns new arrayfilter(fn)- Keep elements that pass a test, returns new array
- Create an array
numberswith values[1, 2, 3, 4, 5] - Use
forEachto log each number multiplied by 2 - Use
mapto create a new arraydoubledwhere each number is doubled - Use
filterto create a new arrayevenswith only even numbers - Log both
doubledandevens
💰 These methods take a callback function:
numbers.forEach((num) => console.log(num))
const squares = numbers.map((num) => num * num)
const big = numbers.filter((num) => num > 10)