Conditional (Ternary) Operator (?:)

By: Dusty Arlia
Published on March 8, 2013
Last Updated on Monday, July 06, 2015 at 2:57 PM
Total Updates: 3

The conditional operator is sometimes called the ternary operator because it has three operands. The first operand comes before the ?. It gets evaluated and returns a true or false value. If the first operand returns true, then the second operand is evaluated and its value is returned. The second operand comes right after the ? and before the :.

If the first operand is false, then the third operand is evaluated and its value returned. The third operand comes after the :. Only the second or third operand will ever get evaluated, never both.

Here is the conditional operator's basic syntax:

operand1 ? operand2 : operand3

These operands can be of any data type or value, but the first operand will return a Boolean value which will decide on whether to return the second or third operand's value.

Here is an example:

news = 'Tell me the';
news_status = 'bad';
news += (news_status == 'good') ? 'good' : 'bad'; 
alert(news);

Comments:

Ad:

Ad: