I have four lines of code like this:
let postId = // <== maybe undefined or string;
const sections = // <== maybe null or an array of sections with posts objects.
postId = postId || (sections ? sections[0]?.posts[0]?.id : null);
console.log(postId || sections ? sections[0]?.posts[0]?.id : null);
The third line is working and I understand why - If postId is falsy, then compute right part of an expression in brackets where I use ternary with optional array item and optional object parameters.
But the fourth line gives me an error:
Uncaught TypeError: Cannot read properties of null (reading '0')
I do not understand why brackets is important in this case.
fourth line gives me an error
The reason behind that is your ternary operator is now working on postId || sections. Hence, Surround your right side statement in parenthesis in order to prevent it to consider left side variable as a part of ternary operation.
It should be :
console.log(postId || (sections ? sections[0]?.posts[0]?.id : null));