# JavaScript Array Tricks: Using map() and filter()
JavaScript provides some powerful methods to manipulate arrays, such as map()
and filter(). These methods can help you write cleaner, more efficient code.
# Using map()
The map() method allows you to create a new array by applying a function to
each element of an existing array. In this example, we create a new array of
squared numbers.
const numbers = [1, 2, 3, 4, 5];
const squared = numbers.map((num) => num * num);
console.log(squared); // Output: [1, 4, 9, 16, 25]
# Using filter()
The filter() method is used to create a new array with only the elements that
pass a certain condition. In this example, we create a new array of even numbers
by filtering the original array using the given condition.
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter((num) => num % 2 === 0);
console.log(evenNumbers); // Output: [2, 4]
By utilizing map() and filter(), you can write more concise and readable
code when working with arrays in JavaScript.