Formsort

Searchâ€¦

Building flows

Handling data

Calculated variables

Create derived variables based on other variables within the flow

Common uses of calculated variables include:

- Formatting answers
- Capturing condition logic that cannot be easily expressed
- Performing math on numbers or dates

Calculated variables behave just like any other answer: they can be used for conditions, templated into most text, and are sent to your analytics and integrations.

Adding a calculated answer

From the **Schema **tab, select **Calculated variables**, and click **Add calculated variable...**

Variable type

Sets the expected data type that we are expecting the calculation to return:

`string`

, `number`

, or `boolean`

Is array?

If **Is array? **is enabled, then we will expect the response to contain multiple answers.

Getter function body

The **Getter function body **contains the Typescript code function body for the calculated answer.

For example, the following getter function body will result in the date 6 months from the current date:

// Getter function body

1

function myFunction(): string {

2

const today = new Date();

3

const d = today.getDate();

4

const future = new Date(today.setMonth(today.getMonth() + 6));

5

if (future.getDate() != d) {

6

future.setDate(0);

7

}

8

return future.toLocaleDateString();

9

}

Copied!

To use existing answers within a getter function body, add the answers as variables. The following calculated variable will calculate the length of the answer variable labelled

`first_name`

The

`myFunction() { ... }`

part of the getter function body is auto-generated and cannot be modified.For more examples on creating calculating variables, see Useful calculated functions at the bottom of this page.

Optional Variables

If any of the parameters to **Optional** field next to the variable.

`myFunction`

are optional, such as in the case of API variables that may or may not be passed in, make sure to check the If a variable that is *not* optional is *not* passed to the function, the Getter function will not execute correctly!

When are calculated variables evaluated?

If a calculated variable has no answer dependencies, it is evaluated at the time that the flow loads.

For calculated variables with dependencies, by default, calculated variables are only evaluated once all of their required (non-*optional*) input variables are defined. If any of the required input variables become undefined, the calculated variable is cleared.

Imagine the following calculated answer, which uses the javascript Math.max function to find the larger of two numbers, and we'll call

`largest_number`

:// Getter function body

1

return Math.max({{number_a}}, {{number_b}});

Copied!

If only one or none of the input answers are defined,

`largest_number`

will remain undefined.1

number_a: undefined

2

number_b: undefined

3

â€‹

4

largest_number: undefined

5

â€‹

6

---

7

â€‹

8

number_a: 17

9

number_b: undefined

10

â€‹

11

largest_number: undefined

Copied!

Only when all of the input answers are defined will the calculation occur.

1

number_a: 17

2

number_b: 48

3

â€‹

4

largest_number: 48

Copied!

For calculated variables with optional dependencies, the calculated variables will be evaluated before the optional dependencies have a value, and will then be re-evaluated whenever an optional dependency receives a value, such as in the case of a responder providing a value for an answer variable.

Conditional evaluation

For more control over when the calculated variable is evaluated, you can set a condition using **Is conditional?**

When using conditional evaluation, you must take care to handle

`undefined`

answers within the getter function body.Using the above example of

`largest_number`

, we could add a condition using Advanced logic to run the calculation whenever either number is defined.// Condition for either number_a OR number_b being defined

1

{

2

"$or": [

3

"number_a": { "$exists": true },

4

"number_b": { "$exists": true },

5

}

6

}

Copied!

Now that we're evaluating the calculation even when the inputs are undefined, we need to change the getter function body to handle this case.

// Getter function body

1

if ({{number_a}} === undefined) {

2

return {{number_b}};

3

} else if ({{number_a}} === undefined) {

4

return {{number_a}};

5

}

6

return Math.max({{number_a}}, {{number_b}});

Copied!

Re-calculate on load

If a calculated variable was calculated in a previous session, and the responder returns to the flow, the default behavior is *not *to re-calculate the answer.

To always recalculate the answer on load, enable **Re-calculate on load**. This is useful for situations when calculated variables are not idempotent, meaning that repeated invocations do not result in the same result, such as answers depending on the current date or time.

â€‹

Useful calculated variable function examples

â€‹

Get age from DOB

We can calculate a responder's age based on the date they enter for answer variable

`patient_dob`

in this example.1

function myFunction(patient_dob: string): number { // readonly line

2

const ageDifMs = Date.now() - (new Date(patient_dob)).getTime();

3

const ageDate = new Date(ageDifMs);

4

return Math.abs(ageDate.getUTCFullYear() - 1970);

5

}

Copied!

Calculate amount of days from today

Using this function, we can calculate the amount of days that have (or will) elapse from a date before or after today.

1

function myFunction(user_defined_date: string): number { // readonly line

2

// turns dates (user_defined_date, today) into ms

3

const date1 = new Date(user_defined_date)

4

const date2 = new Date()

5

â€‹

6

// one day in ms

7

const oneDay = 1000 * 60 * 60 * 24

8

â€‹

9

// calculates time difference between two dates, in ms

10

const timeDiffInMs = date2.getTime() - date1.getTime()

11

â€‹

12

// converts ms to days

13

const diffInDays = Math.round(timeDiffInMs / oneDay)

14

â€‹

15

// return absolute value of the number

16

// prevents negative number returns

17

return Math.abs(diffInDays)

18

}

Copied!

Check responder answer against a list

This function will return a boolean true/false value, based on whether or not the responder's answer to

`State`

is included in a list. 1

function myFunction(State: string): boolean { // readonly line

2

const ineligibleStates = ["DE","HI","LA","MD","MA","NV","NJ","NM","NC","OH","OR","RI","SC","SD","TX","UT"]

3

if (ineligibleStates.includes(State)) {

4

return true

5

}

6

return false

7

}

Copied!

Last modified 4d ago

Copy link

Contents

Adding a calculated answer

Variable type

Is array?

Getter function body

Optional Variables

When are calculated variables evaluated?

Conditional evaluation

Re-calculate on load

Useful calculated variable function examples

Get age from DOB

Calculate amount of days from today

Check responder answer against a list