I have an example similar to this where the first expression evaluates to false and the second is undefined but the overall expression returns undefined into valueResult, shouldn't the first false value terminate the check and return false?
valueResult = false && 10 === 5 ? 'match' : undefined
I have added console log statements and a debugger and this is what is happening, however when I do false && undefined on the browser console, it returns false.
CodePudding user response:
In your updated example, the logical AND … && …
has a higher order of precedence (5) than the evaluation of the ternary … ? … : …
(3).
Check out the table on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#table
CodePudding user response:
&&-operator has higher precedence then the ternary operator. That's why following is happening:
Basically you have a ternary operator (false && (10 === 5) ? : 'match' : undefined
. 10 === 5
evaluates to false and false && false
also results in false. Thats why undefined and not 'match' is returned.
To fix this, add parentheses after && like this:
false && (10 === 5 ? 'match' : undefined)