Ashley Coolman
Ashley Coolman

Reputation: 11585

Javascript: Most effecient way to define variable to a function call, or if null to a variable?

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';

Upvotes: 0

Views: 97

Answers (2)

nnnnnn
nnnnnn

Reputation: 150070

Use JavaScript's logical or operator:

var colour = tryAdventurousColour() || 'black';

Your function tryAdventurousColour() will be executed once. If it returns a "truthy" value then that colour variable will be assigned to that value, otherwise colour will be 'black'. This fits your scenario perfectly since null is a "falsy" value.

In more general terms, the expression a || b returns a if it can be converted to true (is "truthy"), otherwise it returns b. 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.)

Upvotes: 5

Alon Eitan
Alon Eitan

Reputation: 12025

 var colour = (tryAdventurousColour()) ? tryAdventurousColour() : 'black';

Upvotes: -1

Related Questions