Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused by shorthand syntax: x > 0 ? 1 : -1;

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);
like image 531
osami Avatar asked May 12 '12 20:05

osami


3 Answers

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.
like image 75
Madara's Ghost Avatar answered Nov 11 '22 08:11

Madara's Ghost


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.

like image 32
David Heffernan Avatar answered Nov 11 '22 07:11

David Heffernan


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);

like image 1
Robbie Ferrero Avatar answered Nov 11 '22 07:11

Robbie Ferrero