The Methods to Update an Array: Cheat Sheet

banner

ECMAScript 2023 (ES2023 or ES14) introduces a fresh set of array instance methods to enhance the way arrays can be modified.

In total four new methods are added, toSorted() (vs sort()), toReversed() (vs reverse()), toSpliced() (vs splice()), and with (vs bracket notation). These methods use immutable operations on arrays, making it easier and more predictable to work with data without directly modifying the original array.

If you're use TypeScript, these methods are available in version 5.2.

Let's dive into these new methods, and at the same time refresh our knowledge for the existing methods.

Description Mutable Version Immutable Version
Sorts the array sort(compareFn) toSorted(compareFn) - NEW
Reverses the array reverse() toReversed() - NEW
Change an element in the array bracket notation (.[index] = e1) with(index, value) - NEW
Changes the contents of the array splice(start, deleteCount, items?) toSpliced(start, deleteCount, items?) - NEW
Removes the last element pop() slice(0, -1)
Removes the first element shift() slice(1)
Adds element(s) to the end of the array push(e1, e2) concat([e1, e2])
Adds element(s) to the start of the array unshift(e1, e2) toSpliced(0, 0, e1, e2)
Changes all elements within a range to a static value fill(value, start, end?) ❌ Not available
Shallow copies part of this array to another location in the same array copyWithin(target, start, end?) ❌ Not available

For additional details, check out the MDN documentation. Besides the new mutable methods, the ES2023 also added the findLast, and findLastIndex methods for an easy lookup of the last element in an array.

A runnable example can be found in the following the TypeScript Playground.

Support me

I appreciate it if you would support me if have you enjoyed this post and found it useful, thank you in advance.

Buy Me a Coffee at ko-fi.com PayPal logo

Join My Newsletter (WIP)

Join my weekly newsletter to receive my latest blog posts and bits, directly in your inbox.

Share this bit on

Twitter LinkedIn