Jan Tajovsky
Jan Tajovsky

Reputation: 1211

Difference between conditional operator and && || construct

Is there any significant difference in following statements:

$value && 'YES' || 'NO';

and

$value ? 'YES' : 'NO';

Upvotes: 2

Views: 89

Answers (2)

Jamiec
Jamiec

Reputation: 136104

They are more-or-less the same, given your current code. If YES were replaced by something falsey it would be a different story. The below code compares the two with various inputs.

function test1($value){
  return $value && 'YES' || 'NO';
}

function test2($value){
  return $value ? 'YES' : 'NO';
}

function compare(desc, $value){
   console.log(desc, test1($value), test2($value));
}

compare("true",true);
compare("false",false);


compare("truthy1",1);
compare("truthy2","foo");
compare("undefined");
compare("falsey","")

Upvotes: 1

Pointy
Pointy

Reputation: 413717

If you're coding with constants, as in your code samples, then no, there's no difference. In particular, it's important that the constant in the position where you've got "YES" is such a truthy value. However, when you don't know that what the result values are, then yes they're different. Consider:

var x = a ? b : c;

In that code, it is definitely the case that if a is truthy, x will be set to the value of b. If not, it'll be set to the value of c.

Now, on the other hand:

var x = a && b || c;

Here, x will be set to the value of b only if both a and that value are truthy. If b is falsey, then evaluation will move on to the other side of the ||.

Upvotes: 5

Related Questions