Null-value merge operator (??)

Null-value merge operator (??) Is a logical operator that returns the right-hand operand if the left-hand operand is null or undefined, otherwise returns the left-hand operand. Null-value merge operator (??) With the logical or operator (| |), logical or operator will be on the left operand is false value returns the right operand.

const nullValue = null;
const emptyText = ""; // Empty string, false value, Boolean("") === false
const someNumber = 42;

const valA = nullValue ?? "Default values for valA";
const valB = emptyText ?? "Default value for valB";
const valC = someNumber ?? 0;

console.log(valA); // "Default value of valA"
console.log(valB); // "" (null string is false, but not null or undefined)
console.log(valC); / / 42
Copy the code

The optional chain operator (? .).

The optional chain operator (? .) allows you to read the value of a property located deep in the chain of connected objects without explicitly validating that each reference in the chain is valid. (? The.) operator functions like the (.) chain operator, except that it does not cause errors when references are nullish (null or undefined). This expression shorts out the return value of undefined. When used with a function call, returns undefined if the given function does not exist.

The optional chain operator makes the expression shorter and more concise when trying to access an object property that may not exist. The optional chain operator is also helpful when exploring the contents of an object if it is not certain which attributes must exist.

const adventurer = {
  name: 'Alice'.cat: {
    name: 'Dinah'}};constdogName = adventurer.dog? .name;console.log(dogName);
// expected output: undefined

console.log(adventurer.someNonExistentMethod? . ());// expected output: undefined
Copy the code