Home > Back-end >  convert slightly complex "if" statement to ternary operator
convert slightly complex "if" statement to ternary operator

Time:03-28

I have the following code from a project:

setTweetLibrary((curr) => {
    if (!curr[0] || (curr[0] && curr[0].id !== saved_tweets[0].id)) {
        console.log("update");
        return saved_tweets;
    } else {
        console.log("not update");
        return curr;
    }
});

I would like to convert this to a ternary operator with a question mark ("?") to make it neater, but I can't figure out how. Can anyone advise? Thank you!

I think I'm just really confused on how the syntax of ternary operators with multiple conditions and values

CodePudding user response:

As ternary it would look like this:

setTweetLibrary((curr) => {
      return !curr[0] || (curr[0] && curr[0].id !== saved_tweets[0].id)
        ? saved_tweets
        : curr;
});

Note that there is no more place for console.logs. But they seem to be debug anyway.

CodePudding user response:

The ternary operator is not a generic replacement for an if statement, only for choosing between expressions that are going to the same destination.

If we take out the logging, both branches are returning a variable:

if (!curr[0] || (curr[0] && curr[0].id !== saved_tweets[0].id)) {
    return saved_tweets;
} else {
    return curr;
}

The fact that the condition is a long expression doesn't make any difference, it's still equivalent to this:

if (some_condition_goes_here) {
    return saved_tweets;
} else {
    return curr;
}

In that case, you could use a ternary operator to select between the two - move the return to where the if is, and the ? and : before the two values. Then put the whole thing in parentheses to make sure the whole thing is calculated before return:

return (
    (some_condition_goes_here)
    ? saved_tweets
    : curr
);

Specifically:

return (
    (!curr[0] || (curr[0] && curr[0].id !== saved_tweets[0].id))
    ? saved_tweets
    : curr
);

It might be possible to add the logging in there as well, but it will be much harder to read than just using a normal if statement, so if you want that - or any other logic - just stick with if...else.

CodePudding user response:

This works

 return (!curr[0] || (curr[0] && curr[0].id !== saved_tweets[0].id) ? saved_tweets : curr)
  • Related