Ternary operator in Javascript, PHP and in Delphi

This article discusses using of ternary operator, a very usful yet not so famous, logic operator (if counterpart) in Javascript, PHP and… Delphi. Alright, alright. Since Delphi sucks, it is only mentioned here.

Javascript

You can use it in a classic way:

var name = (typeof name === 'undefined') ? 'default value' : name;

or in simplified form of:

var name = name || 'default value';

Bare in mind, that both solutions are not the same!

In first case name will be equal to default value if and only if it was undefined previously. But, in second case it will be equal to default value if it has a value, that evaluates to false.

And in Javascript this means, that this is true if value of name was:

  • 0,
  • null,
  • undefined or
  • “” (empty string).

Because all these values evaluates to false and fulfills condition expressed in second approach.

PHP

Standard usage:

$model->attribute = ($model->attribute == 1) ? 0 : 1;

Bare in mind, that ternary operator is not always an alternative version of if. In some rare occasions using it my dramatically change code’s login. For example:

foreach($data, $key=>$value)
{
if($value == 1) $selected = $key;
}

is not equal to:

foreach($data, $key=>$value)
{
$selected = ($value == 1) ? $key : 0;
}

Because in second approach value of $selected can change back to 0 with ich cycle.

Delphi

In Delphi there is no such thing as ternary operator and IfThen method from Math module is used instead.

As you can see and as you probably know — ternary operator is a very useful thing and this, it is really surprising, that there is no such operator in Delphi, but only a side-method,

Leave a Reply