Here in below code what does ?. and ?? mean
history.replace(loacation.state?.redirectPath ?? '/home')
Here in below code what does ?. and ?? mean
history.replace(loacation.state?.redirectPath ?? '/home')
1. Optional chaining (?.)
From MDN said that
The optional chaining operator (?.) permits reading the value of a property located deep within a chain of connected objects without having to expressly validate that each reference in the chain is valid.
The ?. operator functions similarly to the . chaining operator, except that instead of causing an error if a reference is nullish (null or undefined), the expression short-circuits with a return value of undefined. When used with function calls, it returns undefined if the given function does not exist.
const adventurer = {
name: 'Alice',
cat: {
name: 'Dinah'
}
};
console.log(adventurer.dog?.name); // expected output: undefined
console.log(adventurer.dog.name); // Thow an error message like
//`"message": "Uncaught TypeError: Cannot read property 'name' of undefined",`
2. Nullish coalescing operator (??)
From MDN said that
The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.
const foo = null ?? 'default string';
console.log(foo);
// expected output: "default string"
==> So in case of loacation.state?.redirectPath
is null or undefined
, then value will be '/home'