26
loading...
This website collects cookies to deliver better user experience
x ??= y
will only assign y
to x
if x
is nullish (i.e. null or undefined)// Example 1: x is nullish
let x
const y = 'Chuck Norris'
// ✅ x is assigned 'Chuck Norris'
x ??= y
// Example 2: x is not nullish
let x = 1
const y = 2
// 🔴 x is not assigned 2, its value remains 1
x ??= y
// Translates to this
x ?? (x = y)
// or this
if (x === null || typeof x === 'undefined') {
x = y
}
x ||= y
: this one is similar to ??=
, except it only assigns y
to x
if x
is falsy// Example
let x = 0
const y = 2
// ✅ x is assigned 2
x ||= y
// Translates to this
x || (x = y)
// or this
if (!x) {
x = y
}
x &&= y
is the exact opposite of x ||= y
: it assign y
to x
if x
is truthy// Example
let x = 1
const y = 2
// ✅ x is assigned 2
x &&= y
// Translates to this
x && (x = y)
// or this
if (x) {
x = y
}
// Before
const bigNumber = 19432482347 // => ??? hard to read
// Now
const readableBigNumber = 19_432_482_347 // here we go, much better 😇
String.prototype.replaceAll(searchValue, replaceValue)
String.prototype.replace
which replaced the first occurrence * of a pattern in a string. In order to replace *every occurrence, we had to use a regular expression with the global flag:// String.prototype.replace (searchValue, replaceValue)
const str = "This is a test, I repeat, this is a test"
str.replace(/test/g, 'success')
// output: This is a success, I repeat, this is a success
split
and join
methods:str.split('test').join('success')
// output: This is a success, I repeat, this is a success
replaceAll
method:str.replaceAll('test', 'success')
// output: This is a success, I repeat, this is a success
String.prototype.replace
, searchValue
can be a regular expression, but it has to include a global flag, otherwise it will throw an exception. As mentioned in the proposal:This is done to avoid the inherent confusion between the lack of a global flag (which implies "do NOT replace all") and the name of the method being called (which strongly suggests "replace all").
Promise.any([promise1, promise2, promise3]).then(...).catch(...)
Promise.any
is a new promise method that takes an array of promises and resolves with the value of the first promise to successfully resolve. It will throw an AggregateError
if all the promises are rejected.Promise.any([
fetch('https://v8.dev/').then(() => 'home'),
fetch('https://v8.dev/blog').then(() => 'blog'),
fetch('https://v8.dev/docs').then(() => 'docs')
]).then((first) => {
// Any of the promises was fulfilled.
console.log(first);
// → 'home'
}).catch((error) => {
// All of the promises were rejected.
console.log(error);
});
WeakRef
classFinalizationRegistry
classTheir correct use takes careful thought, and they are best avoided if possible.