Home >Web Front-end >JS Tutorial >Day / Days of Code: Iterating with Methods
Thu, September 5, 2024
Hello everyone! ?
Iterators are yet another JavaScript power tool. In a slight twist, while today’s assignment is named Iterators: .forEach(), .map(), .findIndex(), .filter(), and .reduce(), to be transparent, these are methods that employ iterators to accomplish their purpose.
Iterator Methods Overview
.forEach(): Iterates elements & performs the provided function
.map(): Iterates elements & applies function to create a new array
.findIndex(): Iterates elements, finds match & returns the index
.reduce(): Iterates elements & accumulates values, summation
.filter(): Iterates elements & conditionally creates new array
These methods belong to the Array prototype object and abstract the mundane iterative process to directly expose the data.
Favorite Iterator of the Day: .filter()
After exploring and experimenting with these iterators today, I found that my favorite is .filter() because of its extensibility. A little bit like a factory function, it can be used to create new objects, as long as they’re subsets of the object matching a condition, such as all elements over a certain amount:
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]
That’s so sleek and streamlined that it’s almost beautiful.
Happy coding! ?
The above is the detailed content of Day / Days of Code: Iterating with Methods. For more information, please follow other related articles on the PHP Chinese website!