Logo

Today I Learned

New Immutable Array Methods in ES2023

  1. with changes an array element at a given index without modifying the original:

    javascript
    1const original = ['Hello', 'World'];
    2const modified = original.with(1, 'There');
    3
    4console.log(original); // outputs: ['Hello', 'World']
    5console.log(modified); // outputs: ['Hello', 'There']
  2. toSorted and toReversed respectively sort and reverse an array without modifying the original:

    javascript
    1const original = [6, 4, 7];
    2const sorted = original.toSorted();
    3const reversed = original.toReversed();
    4
    5console.log(original); // outputs: [6, 4, 7]
    6console.log(sorted);   // outputs: [4, 6, 7]
    7console.log(reversed); // outputs: [7, 4, 6]
  3. toSpliced inserts, changes and/or replaces elements in an array without modifying the original:

    javascript
    1const original = ['Jan', 'March'];
    2const modified = original.toSpliced(1, 0, 'Feb');
    3
    4console.log(original);  // outputs: ['Jan', 'March']
    5console.log(modified);  // outputs: ['Jan', 'Feb', 'March']