DEV Community

Usama
Usama

Posted on

🚀 JavaScript Array Non-Mutating Methods Explained (with Examples)

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];
Enter fullscreen mode Exit fullscreen mode

1. map() → Transform elements into a new array

const doubledNum = numbers.map((num) => num * 2);
console.log(doubledNum); // [6, 14, 20, 30, 40, 50]
Enter fullscreen mode Exit fullscreen mode

2. filter() → Keep only elements that match a condition

const greaterNum = numbers.filter((num) => num >= 10);
console.log(greaterNum); // [10, 15, 20, 25]
Enter fullscreen mode Exit fullscreen mode

3. reduce() → Reduce array to a single value

const total = numbers.reduce((acc, cur) => acc + cur, 100);
console.log(total); // 180
Enter fullscreen mode Exit fullscreen mode

4. find() → Find the first element that matches

const arrFind = numbers.find((num) => num % 5 === 0);
console.log(arrFind); // 10
Enter fullscreen mode Exit fullscreen mode

5. some() → Check if at least one element matches

const arrayCheck = numbers.some((ele) => ele === 30);
console.log(arrayCheck); // false
Enter fullscreen mode Exit fullscreen mode

6. every() → Check if all elements match

const positiveNum = numbers.every((num) => num >= 0);
console.log(positiveNum); // true
Enter fullscreen mode Exit fullscreen mode

7. includes() → Check if array contains a value

const includesArr = numbers.includes(50);
console.log(includesArr); // false
Enter fullscreen mode Exit fullscreen mode

8. indexOf() → Find the index of an element

const indexofArr = numbers.indexOf(15);
console.log(indexofArr); // 3
Enter fullscreen mode Exit fullscreen mode

9. flat() → Flatten nested arrays

const flatArr = [1, 2, 3, [50]];
console.log(flatArr.flat()); // [1, 2, 3, 50]
Enter fullscreen mode Exit fullscreen mode

10. flatMap() → Map + flatten in one step

const arrFlatMap = numbers.flatMap((num) => [num * 2]);
console.log(arrFlatMap); // [6, 14, 20, 30, 40, 50]
Enter fullscreen mode Exit fullscreen mode

🎯 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)