frequent
frequent

Reputation: 28513

how variables are set when using multiple OR (||) operators in Jquery/Javascript?

I'm having trouble understanding the order in which an || is executed in Jquery/Javascript.

If I have this:

  someVar = $el.attr("one") || options.two || "three";

it sets someVar to "three" when both $el.attr("one") and options.two are not defined.

I need to add another condition to this statement, like so:

  someVar = $el.attr("one") || options.two || options.extra == "true" ? undefined : "three";

So this should say:

If neither '$el.attr("one")' or 'options.two' are defined, check if 'options.extra == true', if it's true, set to 'undefined', otherwise set to 'three'.

However, I'm always getting undefined even if I set $el.attr("one") and I don't understand why?

Can anyone tell me what is wrong in my logic?

Thanks!

Upvotes: 2

Views: 559

Answers (3)

Tgr
Tgr

Reputation: 28200

The way to write it with logic operators only is

  someVar = $el.attr("one") || options.two || options.extra != "true" && "three" || undefined;

...not that I would use that in actual code. (I probably wouldn't mix logic operators with the conditional operator either.)

Upvotes: 0

Matteo Tassinari
Matteo Tassinari

Reputation: 18584

I think you must put some parenthesis:

someVar = $el.attr("one") || options.two || (options.extra == "true" ? undefined : "three");

in fact your own code is read as:

someVar = ($el.attr("one") || options.two || options.extra == "true") ? undefined : "three";

Upvotes: 8

Christoph
Christoph

Reputation: 51241

The reason is that ? : has a weaker binding than || and therefore is evaluated last. This is the same as if you would write:

( $el.attr("one") || options.two || options.extra == "true" ) ? undefined : "three";

which always will yield undefined as the first expression always is true (because you set $el.attr("one"))

That's why you have to take parens to fix that:

$el.attr("one") || options.two || (options.extra == "true" ? undefined : "three");

Check the operator precedence table, it comes in handy in such cases.

Upvotes: 1

Related Questions