DEV Community

Cover image for JavaScript New Array Methods for Better, Cleaner Code
Honufa Khatun
Honufa Khatun

Posted on

JavaScript New Array Methods for Better, Cleaner Code

New JavaScript comes with a collection of new array methods designed to make code more readable, maintainable, and performant. The methods promote immutability, reduce side effects, and simplify working with arrays. Let’s explore these new, powerful additions to the JavaScript arsenal.

Why Immutability Matters

Most of the traditional array methods like sort(), reverse(), and splice() modify the original array directly. This can lead to issues and bugs, especially in big applications where the same array is accessed somewhere in multiple locations in the code. Immutability, or not modifying data directly, prevents these issues. The new methods we will cover embrace immutability and return new arrays instead of modifying the ones that already exist.

The New Array Methods

The following is an overview of the most significant new array methods and how they can make your coding process easier:

findLast() and findLastIndex(): They are the reverse of find() and findIndex(), but they search for the element from right to left. This is very useful when you need to obtain the last index of an element that meets a certain condition.

const numbers = [1, 5, 3, 5, 2];
const lastFive = numbers.findLast(num => num === 5); // 5
const lastFiveIndex = numbers.findLastIndex(num => num === 5); // 3
Enter fullscreen mode Exit fullscreen mode

toReversed(): Returns a fresh array with elements reversed, leaving the original unchanged. It's a side-effect-free counterpart to the usual reverse() operation.

const originalArray = [1, 2, 3];
const reversedArray = originalArray.toReversed(); // [3, 2, 1]
console.log(originalArray); // [1, 2, 3] (Original array remains unchanged)
Enter fullscreen mode Exit fullscreen mode

toSorted(): Similar to toReversed():, this sorts the array and returns a fresh sorted array without altering the original.

const unsortedArray = [3, 1, 4, 2];
const sortedArray = unsortedArray.toSorted(); // [1, 2, 3, 4]
console.log(unsortedArray); // [3, 1, 4, 2]
Enter fullscreen mode Exit fullscreen mode

toSpliced(): This method is the immutable version of splice(). It returns a new array with the specified changes (deletion or addition of elements), but does not modify the original.

const myArray = [1, 2, 3, 4];
const newArray = myArray.toSpliced(1, 2, 5, 6); // [1, 5, 6, 4] (Removes 2 elements and adds 2)
console.log(myArray); // [1, 2, 3, 4] (Original array remains unchanged)

Enter fullscreen mode Exit fullscreen mode

with(): A more compact replacement for replacing an element at a specified index in an array without modifying the original.

const myArray = [10, 20, 30];
const newArray = myArray.with(1, 25); // [10, 25, 30] (Replaces element at index 1)
console.log(myArray); // [10, 20, 30] (Original array remains unchanged)
Enter fullscreen mode Exit fullscreen mode

Advantages of Using These Functions

Improved Code Readability: These methods are likely to express intent better than their mutable counterparts.
Less Side Effects: Immutability avoids state changes, reducing the likelihood of side effects, which is easier to debug.
Better Maintainability: More readable code is less error-prone and easier to understand, modify, and maintain.
Improved Support for Functional Programming: These approaches are more in line with functional programming, where you can write more supportable and composable code.

Example: Combining Methods

const products = [
    { name: "Apple", price: 1.50 },
    { name: "Banana", price: 0.75 },
    { name: "Orange", price: 1.25 }
];

const sortedAndDiscounted = products
    .toSorted((a, b) => a.price - b.price) // Sort by price
    .with(0, {...products[0], price: products[0].price * 0.9}); // Apply 10% discount to the cheapest item


console.log(sortedAndDiscounted);
Enter fullscreen mode Exit fullscreen mode

These new approaches can be elegantly chained together for sophisticated data transformations:

Browser Compatibility and Polyfills

While these methods are novel, they have solid support in browsers. If you need to support older browsers, however, you can employ polyfills to bridge the gap in the unavailable functionality. A polyfill is a piece of code that brings a new feature to an older environment. Libraries like core-js provide comprehensive polyfills for newer JavaScript features.

Conclusion

These new JavaScript array methods give us a powerful way of writing cleaner, more maintainable, and predictable code. By embracing immutability and minimizing the complexity of common array operations, they make it possible for developers to write more robust and scalable apps. Start incorporating them into your projects today and experience the benefits firsthand!

Top comments (0)