Search code examples
javascriptconditional-operator

How does this nested ternary operator work using javascript?


I am trying to understand what does this nested ternary operator mean using javascript?

below is the code,

const columns = !isUser1Readable
    ? allColumns.filter(column => !columnIdsUser1.includes(column.id))
    : !isUser2Readable
    ? allColumns.filter(column => !columnIdsUser2.includes(column.id))
    : allColumns;

what i have understood?

seems like if isUser1Readable evaluates to false it filters allcolumns array such that it doesn't contain column from columnIdsUser1

if isUser1Readable is true and isUser2Readable is false then filters allcolumns array such that it doesn't contain column from columnIdsUser2

But when does allColumns is assigned to columns?

Could someone help me understand what this nested ternary operator does above. Thanks.


Solution

  • but when does allColumns is assigned to columns?

    In the remaining case, i.e. where both isUser1Readable and isUser2Readable are true.

    The chained ternary expression can be interpreted as an if ... else if ... else sequence:

    let columns;
    if (!isUser1Readable) {
        columns = allColumns.filter(column => !columnIdsUser1.includes(column.id));
    } else if (!isUser2Readable) {
        columns = allColumns.filter(column => !columnIdsUser2.includes(column.id));
    } else {
        columns = allColumns;
    }