The standard library keeps growing. These helpers replace awkward older code. For each, the “added in” is the ECMAScript edition (or a web standard).
| Helper | Replaces | Added |
|---|---|---|
array.at(-1) | array[array.length - 1] | ES2022 |
Object.hasOwn(obj, key) | obj.hasOwnProperty(key) | ES2022 |
str.replaceAll(a, b) | str.replace(/a/g, b) | ES2021 |
array.findLast(fn) | a reversed loop | ES2023 |
array.toSorted(), toReversed(), with() | copy then sort, reverse | ES2023 |
structuredClone(obj) | JSON.parse(JSON.stringify(obj)) | web standard |
Object.groupBy(items, fn) | reduce to group | ES2024 |
at()
const list = ["a", "b", "c"];
console.log(list.at(-1)); // → c
console.log("hello".at(-2)); // → l
Object.hasOwn
const user = { name: "Maya" };
console.log(Object.hasOwn(user, "name")); // → true
console.log(Object.hasOwn(user, "toString")); // → false (inherited, not own)
findLast and findLastIndex
const scores = [10, 25, 30, 18];
console.log(scores.findLast(s => s > 20)); // → 30
console.log(scores.findLastIndex(s => s > 20)); // → 2
Non-mutating array methods
toSorted, toReversed, toSpliced and with return new arrays: Changing Arrays Without Mutating Them.
structuredClone
const original = { a: 1, nested: { b: [1, 2] } };
const copy = structuredClone(original);
copy.nested.b.push(3);
console.log(original.nested.b); // → [1, 2]
Object.groupBy (recent)
Groups items by a key function into an object.
const people = [
{ name: "Maya", team: "web" },
{ name: "Arjun", team: "data" },
{ name: "Sam", team: "web" }
];
if (typeof Object.groupBy === "function") {
const byTeam = Object.groupBy(people, person => person.team);
console.log(Object.keys(byTeam)); // → ["web", "data"]
console.log(byTeam.web.map(p => p.name)); // → ["Maya", "Sam"]
} else {
console.log("Object.groupBy is not supported here");
}
Map.groupBy does the same into a Map. These arrived in ES2024, and all current browsers support them. If you must support older ones, use the reduce pattern or a polyfill.
String helpers
console.log("5".padStart(3, "0")); // → 005
console.log("a-b-c".replaceAll("-", "+")); // → a+b+c
console.log(" hi ".trim().toUpperCase()); // → HI
console.log("abc".at(-1)); // → c
Always feature-detect new things
if (!Array.prototype.toSorted) {
Array.prototype.toSorted = function (compare) { return [...this].sort(compare); };
}
Patching built-ins like this is a polyfill. In real projects, use a well-tested polyfill library or a build tool instead of writing your own. See Browser Support, Polyfills and Transpiling.