javascriptoperator-keywordternary

Operator Precedence in JS between ? and ||


enter image description here

In the image above, I get the value some new value as the output. Could somebody explain me why that is happening? I thought I would get test value as the output but it doesn't seems to be the case. Thanks in advance


Solution

  • The presence of first on the variable object is checked first. Since it is true. the expression passes and "new value" is assigned. The condition will short-circuit, and the 1 > 5 condition will not be need to be checked.

    Note: If the value of first was undefined or falsy, then the 1 > 5 expression would be checked. It would result in false, so the "other value" would be assigned.

    const variable = { first: "test value" }; // variable.first is present
    
    const newVal = (variable?.first || (1 > 5)) ? "new value" : "other value";
    //                      ^ true  OR  ^ false = ^ true value
    
    console.log(newVal); // "new value"