Nullish Coalescing code example
Example 1: nullish coalesing
Expression:
Left ?? Right
if left is null or undefined , then Right will be the value
const a = '' ;
const b = undefined;
const c = a ?? 'default' ;
const d = b ?? 'default' ;
Example 2: logical nullish operator javascript
function config(options) {
options.duration ??= 100;
options.speed ??= 25;
return options;
}
config({ duration: 125 });
config({});
Example 3: nullish-coalescing-operator
null || undefined ?? "foo";
true || undefined ?? "foo";
Example 4: Nullish Coalescing
let x = foo ?? bar();
Example 5: nullish-coalescing-operator
let foo = { someFooProp: "hi" };
console.log(foo.someFooProp?.toUpperCase() ?? "not available");
console.log(foo.someBarProp?.toUpperCase() ?? "not available");