DEV Community

Jacob Stern
Jacob Stern

Posted on • Edited on

Iterating with Methods

Thu, September 5, 2024

(Originally published as part of a 100 Days of Code series. Revised for clarity and purpose.)

Iterators are yet another JavaScript power tool. Today’s assignment was titled Iterators: .forEach(), .map(), .findIndex(), .filter(), and .reduce(), but to be clear—these are methods that use iterators behind the scenes to do their work.

Here’s a quick rundown of what each one does:

.forEach(): Runs a function on each element (but doesn’t return anything)

.map(): Creates a new array by transforming each element

.findIndex(): Returns the index of the first element that matches a condition

.reduce(): Combines elements into a single value (like a sum or total)

.filter(): Returns a new array with only the elements that meet a condition

These methods are part of the Array prototype and handle the repetitive looping for you, letting you focus on the actual data instead.

After trying them all out, .filter() stood out the most for me. It’s clean, powerful, and super flexible—it lets you carve out subsets from an array based on any condition you want. For example, you can use it to pull all elements greater than a certain value, or to isolate all objects with a matching property. It reminds me a little of a factory function: same input shape, different outputs depending on the logic.


const bigNumbers = [148, 256, 384, 918, 512];

// Using filter() to get all elements above 200
const allAbove200 = bigNumbers.filter(num => num > 200);

console.log(allAbove200); // Output: [256, 384, 918, 512]
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
gregharis profile image
Greg Haris

🦾

Great