JavaScript arrays become very powerful when we use arrow functions with methods like map(), filter(), and forEach(). Arrow functions help us write code in a short and clean way.
What is an Arrow Function?
An Arrow Function is a short way to write a function in JavaScript.
It uses the => symbol.
Normal Function
function add(a, b) {
return a + b;
}
Arrow Function
const add = (a, b) => {
return a + b;
};
Short Form
const add = (a, b) => a + b;
Why Use Arrow Functions with Arrays?
Arrow functions are used with arrays because they make code:
short
clean
easy to read
Arrays often need:
- looping
- filtering
- changing values
- finding values
Arrow functions help do these tasks quickly.
Most Used Array Methods
Method | Work |
forEach()
| Loop array |
map()
| Change values |
filter()
| Check condition |
find()
| Find value |
reduce()
| Combine values |
1. forEach() with Arrow Function
forEach() is used to loop through array items.
Example:
let fruits = ["Apple", "Banana", "Mango"];
fruits.forEach((fruit) => {
console.log(fruit);
});
Output:
Simple Meaning
fruit represents each item in array- Arrow function runs for every item
2. map() with Arrow Function
map() creates a new array by changing values.
Example:
let numbers = [1, 2, 3, 4];
let doubleNumbers = numbers.map((num) => {
return num * 2;
});
console.log(doubleNumbers);
Output:
Short Form
let doubleNumbers = numbers.map(num => num * 2);
Simple Meaning
Each number becomes double.
3. filter() with Arrow Function
filter() returns values based on condition.
Example:
let ages = [12, 18, 20, 15, 25];
let adults = ages.filter((age) => {
return age >= 18;
});
console.log(adults);
Output:
Short Form
let adults = ages.filter(age => age >= 18);
Simple Meaning
Only values greater than or equal to 18 are stored.
4. find() with Arrow Function
find() returns the first matching value.
Example:
let numbers = [5, 10, 15, 20];
let result = numbers.find((num) => {
return num > 10;
});
console.log(result);
Output:
Simple Meaning
Only values greater than or equal to 18 are stored.
5. reduce() with Arrow Function
reduce() is used to combine all array values into one value.
Example:
let numbers = [1, 2, 3, 4];
let total = numbers.reduce((sum, num) => {
return sum + num;
}, 0);
console.log(total);
Output:
Simple Meaning
All numbers are added together.
Benefits of Arrow Functions
- Short code
- Easy to read
- Modern JavaScript style
- Useful in Playwright and React
- Best for array methods
Conclusion
Arrow functions make array operations:
- faster
- shorter
- cleaner