Can I run an if statement inside a calculated field?

Ternary operators can get messy for large expressions. A nicer way is to use an immediately-invoked function, this way you can also use js statements as opposed to only js expressions. This can also be more performant if you need to read multiple properties from an expensive object.

{{ (function () {

const item = formatDataAsArray(largeQuery.data).find( ... )
if (item) {
  return `${item.x} - ${item.y}`
} else {
  return "select x and y from the dropdowns above"
}

})() }}

Without the self-invoking function this would need to run formatDataAsArray(largeQuery.data).find( … ) three times.

formatDataAsArray(largeQuery.data).find( ... )
  ? formatDataAsArray(largeQuery.data).find( ... ).x + " - " + formatDataAsArray(largeQuery.data).find( ... ).y
  : "select x and y from the dropdowns above"

Ideally, there would be a way to define functions on a per-app basis similar to transformers. First class JavaScript functions (with workaround)

1 Like