Home Ask Login Register

Developers Planet

Your answer is one click away!

Vishal February 2016

what is the issue in this javascript short circuit assignment

the following javascript code is getting giving undefined as the final output. But as far as I know the OR ' || ' operator will stop the evaluation as soon as it gets "true". But in this block of code it is trying to evaluate the remaining conditions even though it gets true on the first expression.

field = {
    ipaddr: "",
    nodePresentInTopo: false

var bestName = field.ipaddr || (field.ip6addr && field.ip6addr != '::') ? field.ip6addr : undefined || field.sysid;

here bestName always evalueavtes to undefined but why? As it is getting the value at field.ipaddr i.e

please explain the logic.


GMchris February 2016

I'm assuming you know that you've written field.ipaddr instead of fields.ipaddr. Probably for testing purposes. If the last part of the expression is your problem, write it like so:

(undefined || fields.sysid);

RIYAJ KHAN February 2016

I don't think so is there any property with name ip6addr in current object?

var bestName = (field.ipaddr || (field.ip6addr && field.ip6addr != '::') ? field.ipaddr : undefined || field.sysid);

Either you should add ip6addr in current object or replace with appropriate property

deceze February 2016

In one word: operator precedence.

Yes, || short-circuits and doesn't evaluate the second half of the expression used as condition in the ternary operator.

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

Evaluates to:

'' ? .. : ..

Which evaluates to true and then evaluates the true branch of the ternary operator:


If you want a different logical grouping, use parentheses:

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

Post Status

Asked in February 2016
Viewed 3,052 times
Voted 8
Answered 3 times


Leave an answer

Quote of the day: live life