Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 330
frequent Avatar asked Nov 22 '25 03:11

frequent


2 Answers

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";
like image 198
Matteo Tassinari Avatar answered Nov 24 '25 17:11

Matteo Tassinari


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.

like image 42
Christoph Avatar answered Nov 24 '25 16:11

Christoph