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)