# Expression reference (/docs/reference/expressions)



Conditions, calculations and table cells are stored as JSONLogic trees. In the console you write
them in one of three views, covering different levels of detail:

* the **form** (field, operator, value) for simple comparisons. A bare field is a condition too
  (`is true or set` / `is false or empty`). Value fields also take the form: `IF … THEN … ELSE IF …
  ELSE …` rows, and text with `{{field}}` placeholders (`statement-{{account_id}}.pdf`),
* the **formula box**, a short text syntax such as `totalMonthlyDebt / monthlyIncome`,
* the **JSON tree**, for structures such as `eachKey` and operators without text syntax.

Why expressions are pure, and why money does not drift, is in [Expressions are
pure](/docs/concepts/expressions). This page summarizes the vocabulary. See [Rule engine formulas](/docs/reference/formulas)
for the complete operator, alias, precedence and example reference.

## Formula syntax [#formula-syntax]

| Element              | Syntax                                                                                             |
| -------------------- | -------------------------------------------------------------------------------------------------- |
| Numbers              | `42`, `0.35`. Write a very long decimal as text (`'10000000000000000.02'`) to keep full precision. |
| Text                 | `'APPROVED'` or `"APPROVED"`                                                                       |
| Booleans and null    | `true`, `false`, `null`                                                                            |
| Lists                | `['DO', 'US']`                                                                                     |
| Fields               | `amount`, or a dotted path: `customer.risk.level`                                                  |
| Arithmetic           | `+` `-` `*` `/` `%` and unary `-`, with the usual precedence; parentheses group                    |
| Comparison           | `=` `==` `!=` `<>` `>` `>=` `<` `<=`                                                               |
| Membership and range | `country IN ['DO', 'US']`, `amount BETWEEN 1000 AND 2000`                                          |
| Conditional          | `IF amount > 0 THEN amount ELSE 0`, chained with `ELSE IF`; `if(cond, a, b)` is the same call.     |
| Logic                | `AND` / `&&`, `OR` / `\|\|`, `NOT` / `!`; case-insensitive keywords.                               |
| Calls                | `round(2.345, 2)`, `coalesce(blank, fallback)`                                                     |

Arithmetic always compiles to the exact decimal operators, so `0.1 + 0.2` is `0.3`. An unknown
function is rejected when you type it, with the position of the problem, instead of failing at run
time.

## Where fields come from [#where-fields-come-from]

A bare name reads the request payload (`amount`). Three roots are reserved and always addressable:

| Root                      | What it holds                   |
| ------------------------- | ------------------------------- |
| `input.<field>`           | The payload, explicitly.        |
| `vars.<name>`             | Variables set by earlier nodes. |
| `nodes.<node-id>.<field>` | The output of a node.           |

A missing field is `null`, not an error. Decimal comparisons can return true:
`absent = null` and `absent < 0` return `true`. Use
`coalesce` or `is_blank` to say what should happen instead.

## Truthiness [#truthiness]

A condition holds when its value is truthy. These are **false**: `null`, `false`, `0`, `''` (empty
text), `[]` and `{}`. Everything else is true — including the text `'0'` and the list `[0]`.

## Functions [#functions]

### Arithmetic [#arithmetic]

| Function                   | What it does                                                   |
| -------------------------- | -------------------------------------------------------------- |
| `dec_add(a, b, ...)`       | Exact decimal sum. Also available as add.                      |
| `dec_sub(a, b, ...)`       | Exact decimal subtraction. Also available as sub.              |
| `dec_mul(a, b, ...)`       | Exact decimal product. Also available as mul.                  |
| `dec_div(a, b)`            | Exact decimal division. Dividing by zero fails the node.       |
| `dec_mod(a, b)`            | Remainder of an exact decimal division.                        |
| `dec_round(value, places)` | Rounds half away from zero to the given number of decimals.    |
| `dec_abs(value)`           | Absolute value.                                                |
| `dec_neg(value)`           | Negates a value.                                               |
| `dec_min(a, b, ...)`       | Smallest of the operands.                                      |
| `dec_max(a, b, ...)`       | Largest of the operands.                                       |
| `dec_sum(list)`            | Exact sum of a list of numbers.                                |
| `dec_pct(value, percent)`  | Percent of a value, e.g. dec_pct(amount, 15) is 15% of amount. |
| `dec_fixed(value, places)` | Formats to a fixed number of decimals, as text.                |
| `dec_to_number(value)`     | Parses a numeric string into a number.                         |

### Comparison [#comparison]

| Function                           | What it does                                                                              |
| ---------------------------------- | ----------------------------------------------------------------------------------------- |
| `dec_gt(a, b)`                     | True when a is greater than b.                                                            |
| `dec_gte(a, b)`                    | True when a is greater than or equal to b.                                                |
| `dec_lt(a, b)`                     | True when a is less than b.                                                               |
| `dec_lte(a, b)`                    | True when a is less than or equal to b.                                                   |
| `dec_eq(a, b)`                     | True when the two are equal, compared exactly when both are numeric.                      |
| `dec_neq(a, b)`                    | True when the two differ.                                                                 |
| `dec_between(value, lower, upper)` | True when value is within the bounds, inclusive on both sides. Also available as between. |

### Text [#text]

| Function                     | What it does                                                   |
| ---------------------------- | -------------------------------------------------------------- |
| `matches(value, pattern)`    | True when the value matches a regular expression.              |
| `cat(a, b, ...)`             | Concatenates values into one string.                           |
| `substr(text, from, length)` | A slice of a string, counted from zero.                        |
| `len(value)`                 | Length of a string, a list or the number of keys of an object. |

### Lists and objects [#lists-and-objects]

| Function                            | What it does                                                                                  |
| ----------------------------------- | --------------------------------------------------------------------------------------------- |
| `map(list, expression)`             | Transforms every element. The current element is `{"var": ""}` — use `var('')` in formulas.   |
| `filter(list, condition)`           | Keeps the elements whose condition holds. The current element is `{"var": ""}`.               |
| `reduce(list, expression, initial)` | Folds a list into one value. The running value is "accumulator" and the element is "current". |
| `merge(listA, listB, ...)`          | Concatenates lists into one.                                                                  |
| `in(needle, haystack)`              | True when the value appears in the list, or as a substring of the text.                       |
| `all(list, condition)`              | True when every element satisfies the condition. The current element is `{"var": ""}`.        |
| `some(list, condition)`             | True when at least one element satisfies the condition. The current element is `{"var": ""}`. |
| `keys(object)`                      | The key names of an object.                                                                   |
| `val('customer', 'age')`            | Reads path segments from context.                                                             |
| `exists('customer', 'age')`         | True when the path exists, even if it holds `null`.                                           |

### Missing values [#missing-values]

| Function              | What it does                                                 |
| --------------------- | ------------------------------------------------------------ |
| `coalesce(a, b, ...)` | The first operand that is neither null nor blank.            |
| `is_blank(value)`     | True for null, an empty string, whitespace or an empty list. |
| `not_blank(value)`    | True when the value has content.                             |
| `is_null(value)`      | True when the value is null or undefined.                    |

### Dates [#dates]

| Function                 | What it does                                                                             |
| ------------------------ | ---------------------------------------------------------------------------------------- |
| `days_between(from, to)` | Whole days between two dates.                                                            |
| `add_days(date, days)`   | Moves a date by a number of days, returning an ISO timestamp.                            |
| `now()`                  | The execution time. Injected, never read from the clock, so a replay stays reproducible. |

The arithmetic and comparison functions are exact decimals. The plain operators (`+`, `<`) exist
because the underlying JSONLogic engine provides them, but authored formulas compile to the `dec_*`
family; prefer it in hand-written JSON too.

## Dates and the clock [#dates-and-the-clock]

`now()` returns the execution time, injected by the platform; it is never read from the system clock,
so replaying an execution gives the same answer. `days_between` and `add_days` work on ISO dates and
timestamps.

## Regular expressions [#regular-expressions]

`matches(value, pattern)` runs on a linear-time automaton, so no pattern can stall the engine.
Patterns are limited to 500 characters and subjects to 20,000. What needs backtracking —
backreferences (`\1`), lookahead, lookbehind and `\p{…}` — is rejected with an error rather than
run. An invalid or oversized pattern fails the evaluation instead of silently matching nothing.

## Limits and errors [#limits-and-errors]

| Situation                                                   | What happens                            |
| ----------------------------------------------------------- | --------------------------------------- |
| Dividing by zero                                            | The node fails; there is no `Infinity`. |
| Unknown operator or function                                | Rejected: a typo cannot silently pass.  |
| Nesting deeper than 64 levels                               | Rejected.                               |
| A list over 32,768 items or a string over 65,536 characters | Rejected.                               |
| A missing field                                             | `null`; validate presence explicitly.   |

Every evaluation also counts against the execution budget: see [Security
posture](/docs/operate/security#what-one-execution-may-spend).

## Examples [#examples]

| Goal                            | Formula                                      |
| ------------------------------- | -------------------------------------------- |
| Debt-to-income ratio, rounded   | `round(totalMonthlyDebt / monthlyIncome, 2)` |
| 15 % of an amount               | `dec_pct(amount, 15)`                        |
| High value to a watched country | `amount > 10000 AND country IN ['RU', 'NG']` |
| Default when blank              | `coalesce(segment, 'STANDARD')`              |
| Account older than a year       | `days_between(openedAt, now()) > 365`        |
| Code format                     | `matches(code, '^AB\\d+$')`                  |
