I have a requirement to apply the ?? C# operator to JavaScript and I don\'t know how.
Consider this in C#:
int i?=null;
int j=i ?? 10;//j is now
A new operator is currently being added to the browsers, ??=. This is equivalent to value = value ?? defaultValue.
||= and &&= are also coming, links below.
This checks if left side is undefined or null, short-circuiting if already defined. If not, the left side is assigned the right-side value.
let a // undefined
let b = null
let c = false
a ??= true // true
b ??= true // true
c ??= true // false
// Equivalent to
a = a ?? true
let x = ["foo"]
let y = { foo: "fizz" }
x[0] ??= "bar" // "foo"
x[1] ??= "bar" // "bar"
y.foo ??= "buzz" // "fizz"
y.bar ??= "buzz" // "buzz"
x // Array [ "foo", "bar" ]
y // Object { foo: "fizz", bar: "buzz" }
function config(options) {
options.duration ??= 100
options.speed ??= 25
return options
}
config({ duration: 555 }) // { duration: 555, speed: 25 }
config({}) // { duration: 100, speed: 25 }
config({ duration: null }) // { duration: 100, speed: 25 }
??= Browser Support Nov 2020 - 77%
??= Mozilla Documentation
||= Mozilla Documentation
&&= Mozilla Documentation