You can use arrow functions in combination with array methods like forEach and map for concise iteration over an array.
Below are simple examples using arrow functions.
1. Example for forEach() with Arrow Function
let array = [10, 20, 30, 40, 50];
array.forEach(element => {
console.log(element);
});
Output
2. Example for map() with Arrow Function
let array = [10, 20, 30, 40, 50];
let squaredArray = array.map(element => element * element);
console.log(squaredArray);
Output
Note. forEach() will perform the action of the function in the same array itself whereas map() will perform the action and return as a new array.
3. Example for Filter() with Arrow Function
let array = [10, 25, 30, 45, 50];
let evenNumbers = array.filter(element => element % 2 === 0);
console.log(evenNumbers);
Output
4. Example for reduce() with arrow functions
let array = [1, 2, 3, 4, 5];
let sum = array.reduce((a, b) => a + b, 0);
console.log(sum);
Explanations
The code snippet initializes an array with values [1, 2, 3, 4, 5]. Using the reduce method, it sums up the elements of the array, starting with an initial value of 0. The arrow function (a, b) => a + b defines the summation operation, with a as the accumulator and b as the current element. The reduce method iterates through the array, updating the accumulator with the sum of each element. The result, representing the sum of all array elements, is stored in the variable sum, which is then logged to the console using console.log(sum).
Output
5. Example of Find() with Arrow Function
let array = [1, 2, 3, 4];
let foundElement = array.find(element => element > 3);
console.log(foundElement);
Output
These examples show how arrow functions in JavaScript make working with arrays easier. Arrow functions, written like () => {}, are short and easy to read. They help with going through each item, changing elements, picking specific ones, adding them up, and finding certain elements. In simple terms, arrow functions simplify array tasks, and these examples illustrate their usefulness. They are like a shortcut to write code that is both short and clear, making it a preferred choice for array operations in JavaScript.