Codectionary / Developer documentation / JavaScript

Immutable Array Updates with Copying Methods

ES2023 adds toSorted, toReversed, toSpliced, and with as copying alternatives to common array mutations. They create new arrays while retaining the original sequence. Copies are shallow, so referenced objects are still shared; older runtimes need a polyfill or another copying pattern.

Syntax

values.toSorted(compare);
values.toSpliced(index, deleteCount, item);
values.with(index, replacement);

Examples

Immutable Array Updates with Copying Methods: working example

Run this standalone example in a modern browser console unless another environment is specified. Expected result: Logs are 30,5,12; 5,12,30; 12,8,30; and 30,12 on separate lines.

const scores = [30, 5, 12];
const ranked = scores.toSorted((a, b) => a - b);
const corrected = scores.with(1, 8);
console.log(scores.join(","));
console.log(ranked.join(","));
console.log(corrected.toReversed().join(","));
console.log(scores.toSpliced(1, 1).join(","));
  1. Expected result: Logs are 30,5,12; 5,12,30; 12,8,30; and 30,12 on separate lines.
  2. Numeric sorting needs an explicit numeric comparator.
  3. with replaces one position in a fresh array, and toSpliced removes from a fresh array.

Best practices

  • Use copying methods when callers depend on the original array remaining intact.
  • Do not mistake shallow copying for cloning nested records.

Runtime & versions

Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

ECMAScript specification

Specifications & further reading