New language features
JavaScript evolves every year: the TC39 committee approves a new version of the ECMAScript standard, and browsers add new features. This lesson covers small additions that make familiar code shorter and clearer. All of them work in modern browsers and in Node.js.
You can check whether a browser supports a particular feature on the caniuse.com website.
Numeric separators
In long numbers you can put underscores between the digits — that makes them easier to read. They do not affect the number's value:
const salary = 1_250_000;
console.log(salary); // 1250000The at method
The at() method returns an element by its index, like square brackets, but it also understands negative indexes: -1 is the last element, -2 the one before it:
const colors = ['red', 'green', 'blue'];
console.log(colors.at(-1)); // bluePreviously you had to write colors[colors.length - 1]. Strings have the at() method too.
Logical assignment
The ||=, &&= and ??= operators assign a value only under a condition. The one you need most is ??=: it writes the value if the variable or property is null or undefined:
const options = { theme: 'dark' };
options.theme ??= 'light';
options.language ??= 'en';
console.log(options.theme, options.language); // dark enEach of the three operators is shorthand for a longer form:
a ||= b; // a || (a = b)
a &&= b; // a && (a = b)
a ??= b; // a ?? (a = b)findLast and findLastIndex
The find() and findIndex() methods search from the start of an array. Their counterparts findLast() and findLastIndex() search from the end — for example, for the last event of a given type:
const events = [
{ type: 'login', user: 'Anna' },
{ type: 'login', user: 'Oleg' },
{ type: 'logout', user: 'Anna' },
];
const lastLogin = events.findLast((event) => event.type === 'login');
console.log(lastLogin.user); // OlegObject.groupBy
Object.groupBy() sorts the elements of an array into groups. The function returns a group name for each element, and the result is an object where each group has its own array:
const products = [
{ title: 'Apple', type: 'fruit' },
{ title: 'Carrot', type: 'vegetable' },
{ title: 'Pear', type: 'fruit' },
];
const groups = Object.groupBy(products, (product) => product.type);
console.log(groups.fruit.length); // 2
console.log(groups.vegetable[0].title); // CarrotPreviously such grouping was written by hand with reduce().
Common mistake
Mixing up ||= and ??=. The ||= operator fires on any "falsy" value, including 0 and an empty string, and overwrites real data:
const settings = { volume: 0, brightness: 0 };
settings.volume ||= 50;
settings.brightness ??= 50;
console.log(settings.volume); // 50
console.log(settings.brightness); // 0When 0, false or '' are valid values, use ??=.