4

New array methods in JavaScript bring immutability

 1 year ago
source link: https://christianheilmann.com/2023/06/06/new-array-methods-in-javascript-bring-immutability/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

New array methods in JavaScript bring immutability

Tuesday, June 6th, 2023 at 3:57 pm

Scarlet Witch saying no more mutants

JavaScript now has a way to change elements, sort, reverse and splice arrays without changing the original, thus giving it immutability. Four new methods allow you to change arrays without having to create a copy first. The new methods are `with()`, `toSorted()`, `toReversed()` and `toSpliced()`. No need to create a copy with `[...arr]` first. Only missing support in terms of browsers is Firefox.

const arr = ['f','c','k','a','f','d'];
const newArr = arr.with(2,'m');
// newArr -> ['f', 'c', 'm', 'a', 'f', 'd']
const sortArr = arr.toSorted();
// sortArr -> ['a', 'c', 'd', 'f', 'f', 'k']
const reverseArr = arr.toReversed();
// reverseArr -> ['d', 'f', 'a', 'k', 'c', 'f']
const splicedArr = arr.toSpliced(3, 3, 'it');
// splicedArr -> ['f', 'c', 'k', 'it']

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK