How To Use The Conditional Operator
Solution 1:
You are looking at the conditional operator. It is a ternary operator (operator that takes 3 operands), somewhat similar in function to the if statement.
var y = (x > 0) ? x : -x // parenthesis for extra clarity
is almost equivalent to this:
var y;
if (x>0) {
y = x;
} else {
y = -x;
}
A plain text translation is that if the value before the ? evaluates to true, the expression is evaluates to the value before the :
, otherwise it is evaluated to value after the :
.
The conditional operator doesn't need to be used in assignments only. This piece of code does one or another thing depending if x is larger than 0 or not.
x > 0 ? doOneThing(x) : doAnotherThing(x);
However, due to the overlapping functionality with the if statement (explained above), in cases like this, it is often avoided because it is not as clear. In assignments, like the one mentioned in the first example it is clearer and more concise. The if would have some code repetition (y =
) and both branches need to be examined before identifying that that if just assigns a value to y
. With the conditional operator that fact is immediately apparent.
Solution 2:
It is a shorter way of writing the following code:
if(x > 0)
{
//then x
}
else
{
//then -x
}
This syntax is very useful for e.g.
var myvar = (x > 0) ? x : -x;
Solution 3:
That's a ternary operator
if the condition is verified then you run the first part of the statement after (before the :
) else you run the other part.
in the case:
y = x > 0 ? x: -x
you should read this y equal x if x > 0 else y equal -x
Solution 4:
Truthy: Something which evaluates to TRUE. Falsey: Something which evaluates to FALSE.
There are only five falsey
values in JavaScript:
undefined, null, NaN, 0, "" (emptystring), andfalse
Anything other than above is truthy
.
The operator you are using is ternary operator
which behave as:
condition ? execute this expression iftrue : execute this expression iffalse
DEMO
var x = 5;
x > 0 ? x : -x # 5var x = -1;
x > 0 ? x : -x # 1 (positive of -1 as a result of minus operator in -x)
Solution 5:
the ?
is called the ternary
operator and is the only operator to have three operands (three parts to it). The statement reads like an if else statement. The bit before the question mark is the if
statement.
var y = x > 0 ? x : -x;
Could also look like;
if( x > 0 ) {
var y = x;
} else {
var y = -x;
}
Here it is broken down
x > 0 ?
before the question mark is the condition to be met (or if
statement)
?x :
The bit after the question mark but before the colon is the code to run / assign if the condition evaluates to truthy.
: -x
The bif after the colon is the code to run / assign if the condition evaluates to falsy
Post a Comment for "How To Use The Conditional Operator"