Which recent JavaScript features are worth knowing?
The last several editions of JavaScript have added features that remove whole groups of awkward code. These are the ones that come up most often in interviews and in real projects.
ES2020 brought optional chaining and nullish coalescing, which together let you handle missing values safely. The same edition added logical assignment, which lets you write a fallback without repeating the variable name three times.
ES2021 added the numeric separator, so you can write one million as a group of digits instead of a long run of zeros. It also added the replaceAll method, which does the thing that the regular expression flag always made you do before.
ES2022 brought the Object.hasOwn method, which replaces a pattern that used to appear everywhere, together with class fields and the at method on arrays for counting from the end. ES2023 brought the non-mutating array methods, so toSorted, toReversed, toSpliced, and with, along with findLast and findLastIndex. ES2024 brought the array grouping helpers.
// Optional chaining and nullish coalescing.
var settings = { nested: { theme: null } };
console.log(settings?.nested?.theme ?? 'light'); // light
// Logical assignment.
var retries = 0;
retries ||= 3;
console.log(retries); // 3
// The replaceAll method.
console.log('a-b-c'.replaceAll('-', '+')); // a+b+c
// Object.hasOwn, added in ES2022.
var target = { a: 1 };
console.log(Object.hasOwn(target, 'a')); // true
// The at method for indexing from the end.
var letters = ['a', 'b', 'c'];
console.log(letters.at(-1)); // c
// findLast, from ES2023.
console.log([1, 2, 3].findLast(function (n) { return n > 1; })); // 3The grouping helpers are the newest and the most interesting of these. They let you group a collection by a key in a single call, which used to mean writing a reduce with an accumulator every time. The function takes an array and a callback that returns the key for each element, and it gives you back an object and not a map, so the keys are always strings.
There is one caveat to keep in mind about the new array methods. The non-mutating ones, so toSorted and its relatives, are the safer default because they leave the original array alone. The older mutating versions still exist and they are still everywhere in older code, so you need both of them in your head. The grouping helpers are also recent enough that you should check the browser support you need before you rely on them, or you can keep a small helper of your own.