javascript / expert
Snippet
Non-Mutating Array Transformations via ECMAScript Immutable Methods
Modern ECMAScript introduces non-mutating array methods such as toSorted(), with(), and toSpliced(). These return new array instances without altering original arrays, ensuring safe operations on frozen or shared states.
snippet.js
javascript
1
2
3
4
5
6
7
8
const immutableList = Object.freeze([30, 10, 50, 20]);const updated = immutableList.toSorted((a, b) => a - b).with(1, 99).toSpliced(2, 1, 40);console.log('Original:', immutableList);console.log('Updated:', updated);
nodejs
Breakdown
1
const immutableList = Object.freeze([30, 10, 50, 20]);
Creates a frozen array that throws or fails if mutated directly.
2
.toSorted((a, b) => a - b)
Returns a new sorted copy of the array without modifying immutableList.
3
.with(1, 99)
Returns a copy with the value at index 1 replaced by 99.
4
.toSpliced(2, 1, 40);
Returns a copy where 1 item at index 2 is replaced by 40.