1

Can someone please explain to me why the following javascript code produces an alert with 321 and the PHP code produces 1.

I know the PHP code evaluates the expression and returns true or false. What I don't know is why in JavaScript it works like a ternary operator. Is it just the way things were implemented in the language?

var something = false;
var somethingelse = (something || 321);
alert(somethingelse); // alerts 321
$var = '123';
$other = ($var || 321);
echo $other; // prints 1

Thanks!

1
  • in javascript "||" is coalesce oparetor, as short ternary ($a = $b ?: 1) comes with 5.3 Commented Mar 23, 2011 at 22:28

4 Answers 4

4

Is it just the way things were implemented in the language?

Yes, JavaScript does it a bit differently. The expression (something || 321) means if something is of a falsy value, a default value of 321 is used instead.

In conditional expressions || acts as a logical OR as usual, but in reality it performs the same coalescing operation. You can test this with the following:

if ((0 || 123) === true)
    alert('0 || 123 evaluates to a Boolean');
else
    alert('0 || 123 does not evaluate to a Boolean');

In PHP the || operator performs a logical OR and gives a Boolean result, nothing else.

Sign up to request clarification or add additional context in comments.

Comments

0

I'm actually surprised javascript did not alert 1 or true as well. The syntax you want for js is:

var somethingelse = something || 321;

Wrapping parentheses around something evaluates it as truthy / falsey. For php your are saying:

//$other will equal true if $var is true or 321 is true. 
$other = ($var || 321);

A matching statement in php would look like:

$other = ($var) ? $var : 321;

1 Comment

It doesn't matter if the parentheses are there or not.
0

Just to add on boltClock answer since I can't comment - If you want it be a Boolean value you can parse it to bool like this:

var somthing = !!(somthingelse || 321);

Comments

0

In PHP ($var || 321); is evaluated and assigned to $other.

You can use this in PHP.

($other = $var) || $other = 321;

Update: As BoltClock said in Javascript var somethingelse = (something || 321) seeks to assign a default value to the variable if something is false.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.