Search code examples
javascriptjqueryjquery-selectors

In a javascript OR statements, which value is used if both values are defined?


I have the following snippet:

var prevPageWrap = data.prevPage.jqmData("wrapper"),
    pageBackBtn = page.closest('div:jqmData(wrapper="true")').jqmData("usebackbtn"),
    useBackBtn =  pageBackBtn || o.useBackBtn;

if ( useBackBtn && !prevPageWrap ){
    self.crumble(event, data, page );
    }   

My problem is useBackBtn. Im setting usebackbtn to false in my HTML element like so:

<div data-role="page" id="landing" data-wrapper="true" data-scrollmode="overthrow" data-usebackbtn="false">

</div>

which I'm also able to retrieve.

Still

useBackBtn =  pageBackBtn || o.useBackBtn;

is set to true, although pageBackBtn is false.

Question:
If the first "option" is false and the second option is true, what will be the value of useBackBtn = What supercedes what? Is there a shorthand syntax way to say "if the first option is defined, take it, otherwise try the 2nd option?"


Solution

  • If the first "option" is false and the second option is true, what will be the value of useBackBtn = What supercedes what?

    The second option.

    a || b evaluates as a if a is a true value, otherwise it evaluates as b.

    Is there a shorthand syntax way to say "if the first option is defined, take it, otherwise try the 2nd option?"

    Use a ternary operator.

    var a, b, result;
    a = 0;
    b = 1;
    result = typeof a !== "undefined" ? a : b
    alert(result)