Search code examples
javascriptif-statementconditional-operator

convert slightly complex "if" statement to ternary operator


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


Solution

  • 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.