📎 Webclip
The Array Methods Coming to JavaScript in 2022
The page says JavaScript arrays are often copied before changes because updates affect the original array. It presents the “Change Array by Copy” proposal as a way to reduce that pattern with built-in methods that return modified copies instead of mutating the source.
Reading notes#
- JavaScript stores arrays in heap storage, so assigning one array to another keeps the same underlying array.
- Copying with the spread operator is a common workaround before changing an array.
- The “Change Array by Copy” proposal has reached Stage 3.
- The proposal adds four methods:
toReversed(),toSorted(compareFn),toSpliced(start, deleteCount, ...items), andwith(index, value). toReversed()returns a reversed copy of the array.toSorted()returns a sorted copy and accepts a comparison function.toSpliced()returns a copied array with items removed or inserted.with()returns a copied array with one element replaced.- The methods also work on
TypedArrayvalues such asInt8Array. - The page says these methods are not yet supported in major browsers or Node.js, but a polyfill exists.
