ES2023: JavaScript’s Immutability Revolution — New Methods and More!

Jonathan Fielding
3 min readOct 21
Example of the new with method.

Ever since ES2015 was finalised, JavaScript has had yearly ‘releases’ of new features that improve the language and make it easier to work with. In its latest iteration, there has been an increased focus on providing us with more methods that help us use immutability in our JavaScript.

Immutability in JavaScript is where once an object or data structure is created, its contents cannot be changed. The idea is that instead of modifying the original object, any operation to alter it creates a new object with the desired changes, preserving the original’s integrity. As engineers, it allows us to be sure that we don’t cause unintended side effects when we work with data in our code, simplifying debugging and ensuring more maintainable and understandable code.

In this post, we’ll dive into ES2023 and explore what it does to help us use immutability in JavaScript.

The toSorted() Method

The first of our new methods I wanted to touch on is the new toSorted() method, which adds a touch of syntactic sugar to sorting an array without causing a mutation of the original.

Instead of the traditional approach using .sort().

const nums = [7, 2, 3, 12, 1];
const sorted = […nums].sort();
console.log(sorted); // [1, 2, 3, 7, 12]

You can now achieve the same result with toSorted():

const nums = [7, 2, 3, 12, 1];
const sorted = nums.toSorted();
console.log(sorted); // [1, 2, 3, 7, 12]

This is easier to read as you do not have to clone the array yourself first before you sort it.

Additionally, toSorted() accepts a callback function, allowing you to customise the sorting logic, ascending or descending, alphabetical or numeric, similarly to the sort method.

The toSpliced() Method

Another method which helps with avoiding mutating the original value is the new toSpliced() method.

This method resembles splice() and allows you to remove elements from an array without modifying the original, replacing them with new values.

Jonathan Fielding

Staff Engineer working for @Spendesk, speaker about web things, writing about tech, contributor to open source. If you like what I write make sure to follow.