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!
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";
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With