Skip to content
Advertisement

How to split nested ternary operator into normal if else condition

I was trying to understand ternary operator into normal if else condition.

stateable =
data.length > 0
? data[0].list > data[0].somelist
? Product.ADDING
: Product.REMOVING
: Product.NOTHING

how to understand this multiple nested condition

Answer

It’s equivalent to the following:

let stateable;
if (data.length === 0) {
    statable = Product.NOTHING;
} else if (data[0].list > data[0].somelist) {
    statable = Product.ADDING;
} else {
    statable = Product.REMOVING;
}

The conditional operator approach could be refactored to be more readable by putting the NOTHING condition first, though, if you wanted:

const stateable = data.length === 0
    ? Product.NOTHING
    : data[0].list > data[0].somelist
        ? Product.ADDING
        : Product.REMOVING;
Advertisement