user3317823
user3317823

Reputation: 57

how can I turn two statements into a ternary

I have two if statements that'd like to turn into a ternary but I don't know how.

if (val === true && optval === 'car' || val === true && optval === 'truck' )view_list.style.display = 'none';
if (val === true && optval === 'buss' || val === true && optval === 'van')view_list.style.display = '';

Upvotes: 0

Views: 74

Answers (4)

Paul S.
Paul S.

Reputation: 66324

Because nobody has said it yet, switch

if (val === true)
    switch (optval) {
        case 'car':
        case 'truck':
            view_list.style.display = 'none';
            break;
        case 'buss':
        case 'van':
            view_list.style.display = '';
            break;
    }

Upvotes: 1

lorefnon
lorefnon

Reputation: 13095

view_list.style.display = 
  (val === true && optval === 'car' || 
   val === true && optval === 'truck' ) ? 
     'none' : 
     ((val === true && optval === 'buss' || 
       val === true && optval === 'van') ? 
         '' : 
         view_list.style.display ) ;

or more succinctly :

view_list.style.display = 
  (val === true && ( optval === 'car' || optval === 'truck' ) ) ?
     'none' : 
     ((val === true && ( optval === 'buss' || optval === 'van' ) ? 
         '' : 
         view_list.style.display  );

The parentheses around the second conditional are optional.

Of course this is not really a good approach, and this answer should not be seen as an endorsement to this style of programming.

Upvotes: 2

Tim
Tim

Reputation: 2440

Not what you were asking for, but as @dystroy said, this is not the best case for a ternary.

But you can still make it a bit more elegant. How about

var styleMapping = {
    'car': 'none',
    'truck': 'none',
    'buss': '',
    'van': ''
};

// Apparently val is always required in your example
if (val) {
    view_list.style.display = styleMapping[optval];
}

This also has the benefit that refactoring and adding new styles is very easy without having to write much code. Just add one line in the mapping and you're done. And of course it's much more readable and closer to what you intend to do.

You don't really care about boolean logic, you just want to have a different style based on what optval is set to.

Upvotes: 1

Denys Séguret
Denys Séguret

Reputation: 382122

Apart in hacks I won't mention, a ternary is used when you want to return a value in all cases.

If val isn't true, then you do nothing.

Therefore this can't be used here.

Upvotes: 6

Related Questions