ES2023: JavaScript’s Immutability Revolution — New Methods and More!
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)…