I don't know this condition convention in JS(!params?.q). I know the ternary condition but I don't understand this. Can anyone provide insights on this or what should I learn to understand similar conventions?
JS Code Block
if (!params?.q) {// I don't understand a '?' without a ternary //condition
setSkipFirstRender(false);
setSort({
name: PersonEnum.keys.displayName,
dir: PersonEnum.sortOrder.asc,
});
}
CodePudding user response:
The ?.
operator is the optional chaining operator, sometimes also called the Elvis operator.
Despite both using the ?
character, the optional chaining operator and ternary statements serve two different purposes.
Normally if you were to access params.q
and params
was null or undefined, an error would be thrown. What the optional chaining operator allows you to do is safely attempt to access the q
property without an error being thrown. In this case, if params
were null or undefined, params?.q
would evaluate to undefined
.
Essentially this is equivalent to checking if(!(params && params.q))
.
You can read more about the optional chaining operator at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining