I want to write a ternary operator based on the following;
var statusJSON = {
'- Select -': '',
'Active': true,
'Inactive': false
};
Currently I have
statusFlag: $('#statusFlag').val() == 'true' ? true : false
This works fine for true
and false
values, but does not handle the 3rd condition (i.e. empty ""
)
How do I handle the same ?
You can use
statusJSON
as a lookup table:If you're sure that only the three values do occur, or are fine with an
undefined
outcome otherwise, you might as well just useTry to nest the
ternary
operator,You want to use 2 conditionals in the ternary expression, something like:
Your case:
You can just add multiple conditions like this:
()
aren't necessary, but in my opinion, they improve readability when you write it without linebreaks.This means:
So, basically, you're nesting another ternary operator in the
else
clause of the previous one. You can go as far as you'd like with this: