0

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;
  • 1
    i fail to understand what you want to do. what do you want `res` to become? – Layhout Jan 17 '23 at 04:28
  • 1
    Agree with @Layhout. It's unclear what you want `res` to be. Do you simply want `res` to return `true` or `false` based on your condition? – heyitsjhu Jan 17 '23 at 04:30
  • I'd suggest you start with a simple `if` `else` conditional statements to get the logic correct. Ternary operator works as a nice shorthand for simple `if this, else that` conditions, but it can quickly become difficult to reason about. – Bumhan Yu Jan 17 '23 at 04:34

2 Answers2

1

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
wintercounter
  • 7,500
  • 6
  • 32
  • 46
0

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?
             )
Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43
  • if we're looking for a one-liner that returns `true` or `false` we can simply write `i >= 0 && i <= 10`. There's not need to explicitly return `true` or `false` or use a ternary in this case. I, too, thought of this solution but I wonder if this is what the OP is looking for. – heyitsjhu Jan 17 '23 at 04:37
  • 1
    Absolutely true - OP explicitly _asked_ for a solution involving a ternary operator! :D But I very likely misunderstood the question anyway. – Carsten Massmann Jan 17 '23 at 04:38
  • No no, I think you did just that. :) I think we're all a bit confused about the OP's ask but given what was provided, you're right, your answer provided a ternary solution which is what the OP asked. – heyitsjhu Jan 17 '23 at 06:17