When working with arrays in JavaScript, itโs important to understand the difference between mutating and non-mutating methods.
๐ Mutating methods change the original array.
๐ Non-mutating methods return a new array (or value) without altering the original one.
In this post, weโll cover non-mutating methods that every developer should know.
๐ Example Array
const numbers = [3, 7, 10, 15, 20, 25];
1. map()
โ Transform elements into a new array
const doubledNum = numbers.map((num) => num * 2);
console.log(doubledNum); // [6, 14, 20, 30, 40, 50]
2. filter()
โ Keep only elements that match a condition
const greaterNum = numbers.filter((num) => num >= 10);
console.log(greaterNum); // [10, 15, 20, 25]
3. reduce()
โ Reduce array to a single value
const total = numbers.reduce((acc, cur) => acc + cur, 100);
console.log(total); // 180
4. find()
โ Find the first element that matches
const arrFind = numbers.find((num) => num % 5 === 0);
console.log(arrFind); // 10
5. some()
โ Check if at least one element matches
const arrayCheck = numbers.some((ele) => ele === 30);
console.log(arrayCheck); // false
6. every()
โ Check if all elements match
const positiveNum = numbers.every((num) => num >= 0);
console.log(positiveNum); // true
7. includes()
โ Check if array contains a value
const includesArr = numbers.includes(50);
console.log(includesArr); // false
8. indexOf()
โ Find the index of an element
const indexofArr = numbers.indexOf(15);
console.log(indexofArr); // 3
9. flat()
โ Flatten nested arrays
const flatArr = [1, 2, 3, [50]];
console.log(flatArr.flat()); // [1, 2, 3, 50]
10. flatMap()
โ Map + flatten in one step
const arrFlatMap = numbers.flatMap((num) => [num * 2]);
console.log(arrFlatMap); // [6, 14, 20, 30, 40, 50]
๐ฏ Final Thoughts
- These methods donโt mutate the original array.
- Theyโre super useful for functional programming and clean code.
- Once you master these, youโll find writing JavaScript logic much easier and more predictable.
๐ฅ Save this list for your next coding session!
Top comments (0)