user3317823
user3317823

Reputation: 57

how can I turn my if else to a ternary

I can't figure out how to turn my if else statement into a ternary

    if (val === true && optval === 'car')view_list.style.visibility = 'hidden';
      else view_list.style.visibility = 'visible';

Upvotes: 3

Views: 177

Answers (3)

Bucket
Bucket

Reputation: 7521

view_list.style.visibility = (val === true && optval === 'car') ? 'hidden' : 'visible';

In a ternary statement, you have a few different parts:

var = expression ? value_if_true : value_if_false

  • var is optional. You don't have to include it if you don't want to worry about assignment, but in general this is what ternaries are most often used for.
  • expression is the expression to evaluate. Its boolean evaluation is stored for the next part.
  • value_if_true is used if statement is truthy.
  • value_if_false is used if statement is falsey.

Upvotes: 9

erosman
erosman

Reputation: 7721

Clarification: If val has to be Boolean and true, then as mentioned in previous posts, val === true should be used. On the other hand, if it is only checked for true or false, then the following simpler version can be used.

view_list.style.visibility = (val && optval === 'car') ? 'hidden' : 'visible';

Good luck :)

Upvotes: 1

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

do:

view_list.style.visibility = (val === true && optval === 'car') ? "hidden" : "visible";

See Conditional Operators for detailed explanation

Upvotes: 2

Related Questions