Home > Software engineering >  set multiple conditions in ternary operator
set multiple conditions in ternary operator

Time:01-17

I want to set a condition that it should not be greater than 10 or less than 0 but i don't understand how to set in ternary operator

var count = 0;

var res = flag == "1" ?   count : flag == "0" ? --count;

CodePudding user response:

Each condition is returning a result. Let's try to add some formatting. Your's missing the final else statement for the last condition.

var count = 0;

var res =
  flag == "1"
    ?   count
    : flag == "0"
      ? --count
      : doSomethingElse

Anyway, based on what you wrote you want your number to be 0-10. We don't use and -- until we sure we want to write the value. If we're out of range, we simply return the original count value.

var res =
  (count   1) < 10
    ? count  
    : (count - 1 < 0)
      ? count--
      count

CodePudding user response:

Or, in a one-liner form, you can write it like this:

for (let flag=1,count=-4, i=-3; i<15; i  )
  console.log(i,
              i>=0 ? i<=10 ? true : false : false, // using ternary operators 
              i>=0 &&i<=10, // a better way of achieving the same result
              Math.min(Math.max(i,0),10), // maybe this is what you want?
              Math.min(Math.max(flag?  count:--count,0),10) // or this?
             )

  • Related