Search code examples
phpjavascriptevaluationinternalsternary

Difference between PHP and JS evaluation of variables


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!


Solution

  • 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.