Bite-sized JavaScript: Array Prototype methods
Introduction
JavaScript is a versatile language with a wide range of tools available to programmers. One of the most useful features of the language is the Array prototype, which provides a number of powerful methods for working with arrays. In this article, we will explore some of the most commonly used Array prototype methods, along with code examples to illustrate their use.
1. map()
The map() method creates a new array by applying a function to each element of the original array. The function can perform any operation on the element, and the new array will contain the result of that operation.
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map(num => num * 2);
console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]
2. find()
The filter() method creates a new array by removing elements from the original array that do not pass a certain condition. The condition is determined by a function that is passed as an argument.
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // Output: [2, 4]
3. reduce()
The reduce() method takes an array and reduces it to a single value. The value is determined by a function that is passed as an argument. The function takes two arguments, an accumulator and the current element of the array. The accumulator is the accumulated value from previous iterations, and the current element is the current value being processed.
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue);
console.log(sum); // Output: 15
4. forEach()
The forEach() method loops through each element of an array and performs a specified action on each element. The action is determined by a function that is passed as an argument.
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(num => console.log(num)); // Output: 1 2 3 4 5
5. find()
The find() method returns the first element in an array that passes a certain condition. The condition is determined by a function that is passed as an argument.
const numbers = [1, 2, 3, 4, 5];
const evenNumber = numbers.find(num => num % 2 === 0);
console.log(evenNumber); // Output: 2
These are just a few of the many methods available in the Array prototype. By understanding and utilizing these methods, developers can write cleaner, more efficient code for manipulating arrays in JavaScript.
About the author
Joff Tiquez, hailing from Manila, Philippines, is the individual behind the establishment of OSSPH. He is a web developer who strongly supports open source and has been overseeing projects like Vue Stripe for an extended period. To get in touch with Joff, you can visit https://bento.me/jofftiquez.