FrontendDeveloper.in

ECMAScript question detail

Change array by copy

Both Array and TypedArray has built-in methods such as reverse(), sort() and splice() to perform common actions like sorting, reverse the array elements and replacing(or removing) elements. But these methods are mutating the original array. Where as ES2023 has provided additional methods such as toReversed(), toSorted(), toSpliced and with() methods which returns new array copies instead of mutating the original array.

For example, these additional methods returns new array copies for number array without mutating the original array as shown below,

const numbers = [1, 3, 2, 4, 5];

// toReversed
const reversedArray = numbers.toReversed();
console.log(reversedArray); // [5, 4, 2, 3, 1]
console.log(numbers); // [1, 3, 2, 4, 5]

// toSorted
const sortedArray = numbers.toSorted();
console.log(sortedArray); // [1, 2, 3, 4, 5]
console.log(numbers); // [1, 3, 2, 4, 5]

// toSpliced
const splicedArray = numbers.toSpliced(1, 3);
console.log(splicedArray); // [1, 5]
console.log(numbers); // [1, 3, 2, 4, 5]

// with
const replaceWithArray = numbers.with(2, 10);
console.log(replaceWithArray); // [1, 3, 10, 4, 5]
console.log(numbers); // [1, 3, 2, 4, 5]

ES2024 or ES15

ES2024 is planned to be release in June 2024 with a couple of features and enhancements for the developers to make coding in JavaScript more efficient, readable, and robust.

Back to all ECMAScript questions
Get LinkedIn Premium at Rs 399