JavaScript has evolved significantly over the last few years.
Many common coding patterns that developers have been using for a long time now have cleaner, more expressive alternatives. Three particularly useful additions are structuredClone(), Array.prototype.at(), and Array.prototype.findLast().
These features may seem small at first glance, but they can make code easier to read, less error-prone, and more maintainable.
Deep Copying with structuredClone()
Creating a deep copy of an object has always been a challenge in JavaScript. For years, developers relied on hacks such as:
const copy = JSON.parse(JSON.stringify(obj));
While this approach works for simple objects, it breaks when dealing with more complex data types. Dates become strings, Maps and Sets are lost, and circular references cause errors.
A new, better way to make a deep copy of an object is:
const copy = structuredClone(obj);
The structuredClone() function creates a deep copy while preserving many built-in JavaScript types, including Dates, Maps, Sets, TypedArrays, and circular references. The result is more reliable code and less need for third-party libraries.
For most deep-copy scenarios, structuredClone() should now be the default choice.
Easier Array Access with at()
Accessing the last element of an array has traditionally looked like this:
const lastItem = arr[arr.length - 1];
Although common, the expression is somewhat verbose and requires mental arithmetic.
The newer at() method provides a cleaner alternative:
const lastItem = arr.at(-1);
Negative indexes count from the end of the array, making it easy to access the last, second-to-last, or third-to-last item:
arr.at(-1);
arr.at(-2);
arr.at(-3);
The intent is immediately obvious, improving readability and reducing the likelihood of off-by-one errors.
Finding the Last Matching Element with findLast()
Suppose you need the last active user in an array. A common older approach was:
const user = [...users]
.reverse()
.find(u => u.active);
This works, but it creates an additional array and requires multiple operations.
The modern alternative is much simpler:
const user = users.findLast(u => u.active);
The findLast() method searches from the end of the array and returns the first matching element it encounters. The code is shorter, easier to understand, and avoids unnecessary array manipulation.
Conclusion
Modern JavaScript continues to replace old patterns with more expressive language features. As developers, we must stay up-to-date and benefit from that.
These additions discussed in he article may not be as flashy as frameworks or new APIs, but they improve everyday coding.
Top comments (0)