Got this little line here:
var x = trigger ? n : (n-1);
My JS is a bit rusty. What does this do?
Got this little line here:
var x = trigger ? n : (n-1);
My JS is a bit rusty. What does this do?
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.
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.
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
? 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;}