Skip to content
Advertisement

Why does this short circuit evaluation return undefined if first value is false?

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.

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement