8 points
In JavaScript, there exists a ternary (?:) operator. This serves as a shortcut to the if/else conditions. It's a very short operator, allowing only one line of code to be executed in the resulting code block; an alternative would be to make a call to a function but if you need to call more than 1 function for it, just use if/else. Without further ado, let's move on to syntax examples.
The syntax goes like this...
condition ? one line true code : one line false code;Some sample code comparison with
if/else and ?:if(2 > 1) alert('2 is more than 1'); else alert('2 is less than 1');2>1 ? alert('2 is more than 1') : alert('2 is less than 1');A shorter way to do the same operation (but more complex) is the following...
alert('2 is ' + (2>1?'more':'less') + ' than 1');Helping example code can be found at Easily enable and disable this script in which it uses the ternary operator.
login to vote
This is not true to only Javascript, but a few other languages too. It is the 'ternary' operator.
login to vote
In Java it's called the conditional operator.
login to vote
It is ?: operator, not ?
login to vote
The general term is ternary operator http://en.wikipedia.org/wiki/Ternary_operation