javascriptconditional-operatorternaryternary-search

set multiple conditions in ternary operator


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;

Solution

  • 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