js double question mark code example
Example 1: double question mark javascript
//Similar to || but only returns the right-hand operand if the left-hand is null or undefined
0 ?? "other" // 0
false ?? "other" // false
null ?? "other" // "other"
undefined ?? "other" // "other"
Example 2: double question mark in js
const foo = null ?? 'default string';
console.log(foo);
// expected output: "default string"
const baz = 0 ?? 42;
console.log(baz);
// expected output: 0
Example 3: javascript double question mark
let a = null;
const b = a ?? -1; // Same as b = ( a != null ? a : -1 );
console.log(b); // output: -1
//OR IF
let a = 9;
const b = a ?? -1;
console.log(b); // output: 9
//PS.,VERY CLOSE TO '||' OPERATION IN FUNCTION, BY NOT THE SAME
Example 4: 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' ; // will give c =''
const d = b ?? 'default' ; // wil give d = 'default'
Example 5: logical nullish operator javascript
function config(options) {
options.duration ??= 100;
options.speed ??= 25;
return options;
}
config({ duration: 125 }); // { duration: 125, speed: 25 }
config({}); // { duration: 100, speed: 25 }