what is the issue in this javascript short circuit assignment -


the following javascript code getting giving undefined final output. far know or ' || ' operator stop evaluation gets "true". in block of code trying evaluate remaining conditions though gets true on first expression.

field = {     ipaddr: "0.0.0.0",     nodepresentintopo: false }  var bestname = field.ipaddr || (field.ip6addr && field.ip6addr != '::') ? field.ip6addr : undefined || field.sysid; 

here bestname evalueavtes undefined why? getting value @ field.ipaddr i.e 0.0.0.0

please explain logic.

in 1 word: operator precedence.

yes, || short-circuits , doesn't evaluate second half of expression used condition in ternary operator.

field.ipaddr || (field.ip6addr && field.ip6addr != '::') ? .. : .. 

evaluates to:

'0.0.0.0' ? .. : .. 

which evaluates true , evaluates true branch of ternary operator:

field.ip6addr 

if want different logical grouping, use parentheses:

field.ipaddr || (.. ? .. : ..); 

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -