KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: How to chain ternary conditional operator
PRODUCT: 4D | VERSION: 20 | PLATFORM: Mac & Win
Published On: April 15, 2024

The ternary operator allows “If...Else...End if” control flow structure to be written in a single line. For example, consider the following statement:

If ($myAge<=$yourAge)
   $greeting:="Hello, sir."
Else
   $greeting:="Hello, kid."
End if

It can be re-written using ternary operator as follows:

$greeting:=$myAge<=$yourAge ? "Hello, sir." : "Hello, kid."

An additional condition can be chained to the above, for instance:

$greeting:=$myAge<$yourAge ? "Hello, sir." : $myAge>$yourAge ? "Hello, kid." : "Hello, peer."

This is the same as the following statement:

If ($myAge<$yourAge)
   $greeting:="Hello, sir."
Else
   If ($myAge>$yourAge)
     $greeting:="Hello, kid."
   Else
     $greeting:="Hello, peer."
   End if
End if

As demonstrated above, the ternary operator can be chained to condense multiple conditions into one line.