Member-only story
What’s new in ECMAScript 2023 (ES14)
The 14th edition of the ECMAScript standard, ECMAScript 2023, introduced several new methods mainly for Array.prototype
and TypedArray.prototype
. In this post we go through some of these new methods which will do operations over arrays more efficient.
- toSpliced()
You can use toSpliced()
to delete, add, and replace elements in an array and create a new array more efficiently than using slice()
and concat()
.
const fruits = ["Apple", "Banana", "Orange", "Grapes"];
// Inserting an element at index 1
const fruits2 = fruits.toSpliced(1, 0, "Mango");
console.log(fruits2); // ["Apple", "Mango", "Banana", "Orange", "Grapes"]
// Deleting two elements starting from index 2
const fruits3 = fruits2.toSpliced(2, 2);
console.log(fruits3); // ["Apple", "Mango", "Grapes"]
// Replacing one element at index 1 with two new elements
const fruits4 = fruits3.toSpliced(1, 1, "Kiwi", "Pineapple");
console.log(fruits4); // ["Apple", "Kiwi", "Pineapple", "Grapes"]
// Original array is not modified
console.log(fruits); // ["Apple", "Banana", "Orange", "Grapes"]
The
toSpliced()
method always creates a dense array.
Read more about this method.
- toSorted()
The toSorted()
method is like sort()
, but it returns a new sorted array, leaving the original array…