Nested Conditional Operators

Avalander - Jan 30 '19 - - Dev Community

Cover image by Talles Alves on Unsplash

Internet wisdom says that nested conditional operators are evil. And I firmly believed internet wisdom until today.

Today I found myself refactoring some old Javascript code and it had one of those functions that validate that a heckload of properties exist and have the right format in an object. Then I went crazy and wrote something similar to this.

const validateInput = ({ field1, field2, field3 }) =>
    (!field1
        ? Promise.reject('Missing field1')
        : !Array.isArray(field2)
        ? Promise.reject('field2 is not an array')
        : !isValidType(field3)
        ? Promise.reject('field3 is invalid')
        : Promise.resolve()
    )

Don't mind the thing with promises, this function is used inside a promise chain.

The thing is, it makes me cringe a bit because, you know, nested conditional operators are evil, but I actually find it readable, and I'd say it might even flow better than the chain of ifs.

I would like to read your thoughts and opinions in the topic. Are nested conditional operators inherently evil and unreadable or are they alright, they have just been used in a messy manner for too long?

. . . . . . . . . . . . . . . . . . .
Terabox Video Player