Immutable Array Methods: toSorted, toReversed, toSpliced, and with
JavaScript has introduced new array methods that provide immutable alternatives to their mutable counterparts. These methods create new arrays instead of modifying the original, making them perfect for state management in modern frameworks and functional programming.
toSorted()
Creates a new sorted array without modifying the original:
const numbers = [3, 1, 4, 1, 5];
const sorted = numbers.toSorted();
console.log(sorted); // [1, 1, 3, 4, 5]
console.log(numbers); // [3, 1, 4, 1, 5] - original unchanged
// Custom sorting
const fruits = ['banana', 'apple', 'orange'];
const sortedFruits = fruits.toSorted((a, b) => a.localeCompare(b));
console.log(sortedFruits); // ['apple', 'banana', 'orange']
toReversed()
Returns a new array with elements in reversed order:
const original = [1, 2, 3, 4, 5];
const reversed = original.toReversed();
console.log(reversed); // [5, 4, 3, 2, 1]
console.log(original); // [1, 2, 3, 4, 5] - original unchanged
toSpliced()
Creates a new array with deleted or inserted elements:
const colors = ['red', 'green', 'blue'];
// Remove one element starting at index 1
const removed = colors.toSpliced(1, 1);
console.log(removed); // ['red', 'blue']
console.log(colors); // ['red', 'green', 'blue']
// Insert elements without removing any
const inserted = colors.toSpliced(1, 0, 'yellow', 'purple');
console.log(inserted); // ['red', 'yellow', 'purple', 'green', 'blue']
with()
Returns a new array with a single element replaced at the given index:
const items = ['apple', 'banana', 'orange'];
const newItems = items.with(1, 'grape');
console.log(newItems); // ['apple', 'grape', 'orange']
console.log(items); // ['apple', 'banana', 'orange']
Performance Considerations
Memory Usage
These methods create new arrays, which means additional memory allocation. For very large arrays or high-frequency operations, this could impact performance. Consider using mutable methods in performance-critical loops where immutability isn't required.
Benchmarks
// Performance comparison
const largeArray = Array.from({ length: 100000000 }, (_, i) => i);
console.time('sort');
largeArray.sort();
console.timeEnd('sort') // sort: 1935.779ms;
console.time('toSorted');
largeArray.toSorted();
console.timeEnd('toSorted') // toSorted: 3161.522ms;
// toSorted is typically 2-3x slower due to array copying
When to Use Immutable Methods
- When working with state management in React, Vue, or similar frameworks
- In functional programming patterns where immutability is desired
- When you need to preserve the original array for comparison or history
- In situations where code clarity is more important than raw performance
Browser Support
These methods are relatively new and might require a polyfill for older browsers. Check browser support before using in production.