function getId(user, fallback) {
return user && user.id ?? fallback;
}
The ?? operator has higher precedence than the && operator. This means that the expression user && user.id ?? fallback is equivalent to user && (user.id ?? fallback). This is not what we want. We want to return fallback if user is null or undefined, and user.id otherwise.
To fix this, we need to use parentheses to change the order of evaluation:
function getId(user, fallback) {
return (user && user.id) ?? fallback;
}
or even better, just use optional chaining:
function getId(user, fallback) {
return user?.id ?? fallback;
}