re: If/else or just if? VIEW POST


Another option (for those who favour expressions over statements) can be built out of JavaScript's ternary operator:

return (typeof val === 'string') ? 'A'
     : (val === null || val === undefined) ? 'B'
     : val

Quite a popular pattern.


Ternary operators are really nice for simple and small statements, but I definitely wouldn't recommend them for anything complex. Makes things to hard to read for me. The same could be said for other developers.


I always put a LOT of parentheses around the ternary operators, and enforce a style that looks like this:

((typeof val === 'string')
 ? 'A'
 : ((val === null || val === undefined)
    ? 'B'
    : val))

In general, I consider operator precedence to be a footgun, as it makes things more complex than they need to be. I find symbolic expressions to be much more readable, as there is no need to even understand what functions do to see the order of application.

code of conduct - report abuse