Pilcrow Records

Scripter Javascript Tutorial

javascriptmusiclogicscripterbookexcerpttutorial

63 The Conditional (Ternary) Operator

MDN: Operators: Conditional Operator

The Conditional (ternary) operator is a concise version of the if...then operator, ideal for small tests which really only need one line of code. The Conditional operator accepts 3 operands, all of which are wrapped in parentheses, “(...)”:

( <condition> ? <condition is true> : <condition is false> );
  1. A condition to be tested following by a question mark “?”.

  2. An expression to be executed when the condition is true, followed by a colon “:”.

  3. An expression to be executed when the condition is false.

function testPitchForMiddleC( pitch ) {
	return ( pitch == 60 ? true : false ); 
}

In the above example, a simple function is declared to test whether a passed integer equals Middle C, MIDI pitch 60. In line 2, the pitch is tested to see if it equals 60, before the question mark. When true, the boolean true value is returned, before the colon. When false, false is returned.

Using the Conditional operator is really a matter of style and is typically used in short tests which don’t need all of the syntax of a full if operator.