I have often used the following construct in Javascript:
var foo = other_var || "default_value";
In Javascript, if the left side is falsy, then the value on the right side is assigned.
It is very handy, and saves writing longer and unnecessarily explicit ternary expressions.
Is there a name for this sort of construct ?
Bonus: Is there a trick to do this in Php without using a ternary operator?
PS: another variant is to throw an error if you don’t get a truthy value, instead of giving a default value:
var foo = something || alert("foo is not set!");
The logical-or (usually
||) operator is drastically different in many languages.In some (like C, C++) it works like: “Evaluate the left-hand side; if it’s true, return true, otherwise evaluate the right hand-side and return true if it’s true or false otherwise.” The result is always boolean here.
In others (like Javascript, Python, I believe that PHP also) it’s more like: “Evaluate the left-hand side; if it’s true, return it, otherwise evaluate the right-hand side and return the result.” Then the result can be of any type and you can do constructs like:
a = (b || c); // equivalent to a = b ? b : c;or quite fancy: