Conditional special operator JS Home  <<  JS Reference  <<  Conditional

Shorthand conditional true/false operator.

Description

The conditional operator takes three operands and is often used as a shortcut replacement for the if....else statement. The operator consists of a condition and two expressions

  • The value of the first expression is returned if the condition evaluates to true.
  • The value of the second expression is returned if the condition evaluates to false.

Syntax

Signature Description
condition ? expressionIfTrue : expressionIfFalseThe conditional operator.

Parameters

Parameter Description
conditionExpression that evaluates to true or false.
expressionIfTrueThe expression value to use for true.
expressionIfFalseThe expression value to use for false.

Examples

Following is an example of the conditional operator.


// The conditional operator.
var aBoolean = 'true';

alert((aBoolean == 'true' ? 'Evalutes to true' : 'Evalutes to false')); 
alert((aBoolean == 'false' ? 'Evalutes to true' : 'Evalutes to false'));}

Press the button below to action the above code:

Related Tutorials

JavaScript Advanced Tutorials - Lesson 1 - Advanced Conditional Statements