0

Got this little line here:

var x = trigger ? n : (n-1);

My JS is a bit rusty. What does this do?

user1369594
  • 183
  • 10

5 Answers5

1

It's just a simple ternary operator.

If trigger is true-like, x becomes n, otherwise it becomes n-1.

Here's a page from Mozilla showing some of the things you can do with the ternary operator.

Antimony
  • 37,781
  • 10
  • 100
  • 107
0

if trigger true then x becomes n otherwise n-1

The conditional operator is used as a shortcut for standard if statement. It takes three operands.

Condition ? expr1 : expr2

condition : An expression that evaluates to true or false.

expr1, expr2 : Expressions with values of any types.

If condition is true, the operator returns the value of expr1; otherwise, it returns the value of expr2.

SEE HERE

PSR
  • 39,804
  • 41
  • 111
  • 151
0

If trigger is truthy then x = n else x = n-1

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

If condition trigger is true, then x = n. If trigger is false, then x = n - 1;

Quick tests:

<script>
    var trigger = false, n = 7;
    var x = trigger ? n : (n-1);
    alert( x );
</script>

<script>
    var trigger = true, n = 7;
    var x = trigger ? n : (n-1);
    alert( x );
</script>

More in here about "Conditional Operator":

http://msdn.microsoft.com/en-us/library/ie/be21c7hw%28v=vs.94%29.aspx

0

? is a conditional Operator: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Conditional_Operator

Essentially it is equivalent to:

if (x) { x=n; } else { x=n-1;}
  • With the important difference that the operator is a expression (i.e. it has a value), where if then else is a statement. – schlicht Apr 27 '13 at 13:19