javascript - What is this assignment construct called? And can you do it in Php? -


i have used following construct in javascript:

var foo = other_var || "default_value"; 

in javascript, if left side falsy, value on right side assigned.

it handy, , saves writing longer , unnecessarily explicit ternary expressions.

is there name sort of construct ?

bonus: there trick in php without using ternary operator?

ps: variant throw error if don't truthy value, instead of giving default value:

var foo = || alert("foo not set!"); 

the logical-or (usually ||) operator drastically different in many languages.

in (like c, c++) works like: "evaluate left-hand side; if it's true, return true, otherwise evaluate right hand-side , return true if it's true or false otherwise." result boolean here.

in others (like javascript, python, believe php also) it's more like: "evaluate left-hand side; if it's true, return it, otherwise evaluate right-hand side , return result." result can of type , can constructs like:

a = (b || c); // equivalent = b ? b : c;

or quite fancy:

function compare(a, b) { // -1 if a<b, 0 if a==b, 1 if a>b     return b.x - a.x || b.y - a.y; } 

Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

html - Instapaper-like algorithm -

c# - How to execute a particular part of code asynchronously in a class -