map(), filter(), reduce()

Introduction

In modern JavaScript, working with arrays efficiently is very important. The methods map, filter, and reduce are powerful tools that help developers process and transform data in a clean and readable way. These methods are commonly used in web development and are essential for beginners and professionals.

Understanding map Method

The map method is used to create a new array by applying a function to each element of an existing array. It does not change the original array.

Example

const numbers = [1, 2, 3, 4];

const doubled = numbers.map(function(num) {
return num * 2;
});

console.log(doubled);

In this example, each number is multiplied by 2, and a new array is returned.

Use Cases of map

Transforming data
Converting values
Updating items in an array

Understanding filter Method

The filter method is used to create a new array that includes only the elements that meet a specific condition.

Example

const numbers = [1, 2, 3, 4, 5];

const evenNumbers = numbers.filter(function(num) {
return num % 2 === 0;
});

console.log(evenNumbers);

This example returns only even numbers from the array.

Use Cases of filter

Selecting specific data
Removing unwanted values
Searching within arrays

Understanding reduce Method

The reduce method is used to process all elements of an array and return a single value. It is often used for calculations like sum, total, or aggregation.

Example

const numbers = [1, 2, 3, 4];

const sum = numbers.reduce(function(total, num) {
return total + num;
}, 0);

console.log(sum);

This example calculates the total sum of all numbers in the array.

Use Cases of reduce

Calculating totals
Combining data
Creating summaries

Key Differences

map returns a new array with transformed values
filter returns a new array with selected values
reduce returns a single value after processing all elements

Best Practices

Use arrow functions for cleaner code
Keep functions simple and readable
Avoid modifying the original array
Choose the right method based on your goal

Conclusion

The map, filter, and reduce methods are essential for writing efficient and clean JavaScript code. Mastering these will improve your ability to handle data and build modern applications.

Home ยป Intermediate JavaScript > Arrays > map(), filter(), reduce()