I came across a puzzling scenario while using a ternary operator within the .find method of an array. In my search for an object:
Consider this:
const list = [
{ id: 1, name: "dave"},
{ id: 3, name: "choi"},
{id: 4, name: "bob"}
]
// this works
let isBoy = true
console.log(list.find(v => v.name === isBoy ? "dave" : "choi"))
// this don't work
isBoy = false
console.log(list.find(v => v.name === isBoy ? "dave" : "choi"))
// this always works: use () around ternary
console.log(list.find(v => v.name === (isBoy ? "dave" : "choi")))
isBoy = true
console.log(list.find(v => v.name === (isBoy ? "dave" : "choi")))
What surprised me was that
// this don't work
isBoy = false
console.log(list.find(v => v.name === isBoy ? "dave" : "choi"))
It will return "dave"
instead of "choi"
. This led to a very challenging bug to locate today. Can anyone explain what exactly is happening here and why it behaves like this?
Why do parentheses make a difference? What resources should I refer to in order to grasp this concept better? Is it related to the order of operations? My javascript IDE linter did not indicate any issue or warning, which it usually does with similar precedence matters.
My Attempts
I attempted to find similar SA queries that could provide insights into this issue but could not find an explanation for what puzzled me.