Using ternary operator requires two calls to the function.
var colour = (tryAdventurousColour() != null) ? tryAdventurousColour() : 'black';
Possible to do it in 1 line?
EDIT: Fixed syntax
EDIT: Like this but better
var colour = ( (colour = tryAdventurousColour() ) != null ) ? colour : ‘black’;
Use JavaScript’s logical or operator:
Your function
tryAdventurousColour()will be executed once. If it returns a “truthy” value then thatcolourvariable will be assigned to that value, otherwisecolourwill be ‘black’. This fits your scenario perfectly sincenullis a “falsy” value.In more general terms, the expression
a || breturnsaif it can be converted to true (is “truthy”), otherwise it returnsb. Note that non-zero numbers, non-empty strings and objects will all be converted to true.null, undefined, 0, “” will all be converted to false. (I’m sure somebody will correct me if I’ve left something out.)