What does the following Javascript syntax mean? Please describe the whole syntax:
var x = 0;
x > 0 ? 1 : -1; // confused about this line
alert(x);
That on its own means nothing. You will alert x
's value, which is 0, and that's it. The second statement is meaningless unless you assign it to something. If however you would have done this:
var x=0;
var y = x > 0 ? 1 : -1;
alert(y);
You would have gotten -1.
The Conditional Operator, is a shorthand for IF statements, it basically says:
Assert if
x > 0
. If so, assign 1. If not, assign -1.
Or on a more general form:
CONDITION ? VALUE_IF_TRUE : VALUE_IF_FALSE;
Where:
CONDITION
- can be anything which evaluates to a boolean (even after type juggling).VALUE_IF_TRUE
- value to be returned in case CONDITION
was asserted to TRUE
.VALUE_IF_FALSE
- value to be returned in case CONDITION
was asserted to FALSE
.That is the conditional operator. It is a ternary operator because it has three operands. It is often referred to as the ternary operator but that terminology is rather loose since any operator with three operands is a ternary operator. It just so happens that is is the only commonly used ternary operator.
What does it mean? The expression
a?b:c
evaluates to b
if a
evaluates as true, otherwise the expression evaluates to c
.
this is a ternary operator (the ?)
Think of it like an IF statement.
the statement before the '?' is the condition of your if statement. Immediately what follows before the ':' is what will execute/be-assigned if the statement is true. After the ':' is what will execute/be-assigned if the statement is false.
Your code however will just alert 0 because you aren't assigning anything from your ternary operator.
basically your code might as well say.x = 0;
alert(x);
// this would alert 0
you need to revise this to:x = 0;
var y = x > 0 ? 1 : -1;
alert(y);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With