Search code examples
javascriptif-statementternary

Try to figure it out how to translate a long ternary operator with more than one condition into long if statement


I found online this snippet and I'm trying to figure it out how to translate it in a plan if statement:

return a.price > b.price ? 1 : a.price === b.price ? a.name > b.name ? 1 : -1 : -1;

In my opinion, if I had written an if statement:

if (a.price > b.price) {
    return 1;
} else if (a.price === b.price) {
    return 1;
} else if (a.name > b.name) {
    return 1;
} else {
    return -1;
}

But I'm not quite sure what it means a question mark and right after another question mark, same problem with a colon. I get that, the colon, in this case, could be an else if statement (in that order), but what about the question mark? any hint?


Solution

  • Grouping it like this will help

    a.price > b.price ? 1 : (a.price === b.price ? (a.name > b.name ? 1 : -1) : -1)

    a.price > b.price ? 1 : x
    x = a.price === b.price ? y : -1;
    y =  a.name > b.name ? 1 : -1; 
    

    The translated IF ELSE would be

    if(a.price > b.price){
        return 1
    } else {
        if(a.price === b.price){
            if(a.name > b.name){
                return 1;
            } else {
                return -1;
            }
        } else {
            return -1;
        }
    }