Expression:
Left ?? Right
if left is null or undefined , then Right will be the value
const a = '' ;
const b = undefined;
const c = a ?? 'default' ; // will give c =''
const d = b ?? 'default' ; // wil give d = 'default'
console.log(<left-operand> <operator> <right-operand>);
// same behaviour
console.log(undefined || "John"); // "John"
console.log(undefined ?? "John"); // "John"
console.log(null || "John"); // "John"
console.log(null ?? "John"); // "John"
// different behaviour
console.log(0 || "John"); // "John"
console.log(0 ?? "John"); // 0
console.log("" || "John"); // "John"
console.log("" ?? "John"); // ""
console.log(false || "John"); // "John"
console.log(false ?? "John"); // false
//nullish coalescing operator in js
Expression:
Left ?? Right
if left is null or undefined , then Right will be the value
let value = null ?? "Oops.. null or undefined";
console.log(value) //Oops.. null or undefined
value = undefined ?? "Oops.. null or undefined";
console.log(value) //Oops.. null or undefined
value = 25 ?? "Oops.. null or undefined";
console.log(value) // 25
value = "" ?? "Oops.. null or undefined";
console.log(value) // ""
(null || undefined) ?? "toto"; // Renvoie "toto"
null || undefined ?? "foo"; // raises a SyntaxError
true || undefined ?? "foo"; // raises a SyntaxError
let x = foo ?? bar(); // return foo if it's not null or undefined otherwise calculate bar
alert(username ?? "Guest");
let foo = { someFooProp: "hi" };
console.log(foo.someFooProp?.toUpperCase() ?? "not available"); // "HI"
console.log(foo.someBarProp?.toUpperCase() ?? "not available"); // "not available"