---
type: "fhirpath-function"
title: "FHIRPath Function: defineVariable"
function: "defineVariable"
category: "Utility functions"
section: "5.10.4"
source: "fhirpath/functions.json"
---
# FHIRPath Function: defineVariable
{:.stu}
> **Note:** The contents of this section are Standard for Trial Use (STU)
{: .stu-note }
Defines a variable named `name` that is accessible in subsequent expressions on the output collection and has the value of `projection` if present, otherwise the value of the input collection. In either case the function does not change the input and the output is the same as the input collection.
{:.stu}
> **Note:** This is not a scoped function, it does not change any variables such as `$this` or `$index`.
>
> This function is the only function that changes the state of the context for processing on the output collection.
> Whereas [scoped functions](#scoped-functions) only impact the context while evaluating the function, and it's parameters, and the context is restored to the same as before the function was called.
{:.stu}
If the name already exists in the current expression scope, the evaluation will end and signal an error to the calling environment.
{:.stu}
Example:
{:.stu}
``` fhirpath
group.select(
defineVariable('grp')
.select(
element.select(
defineVariable('src')
.target.select(
%grp.source & '#' & %src.code
& ' ' & equivalence & ' '
& %grp.target & '#' & code
)
)
)
)
```
{:.stu}
> **Note:** this could be implemented using expression scoping on the variable stack and after expression completion the temporary variable would be popped off the stack.
{:.stu}
## Summary
- **Category**: Utility functions
- **Section**: `5.10.4`
- **Return Type**: `collection`
- **Empty Input Result**: `empty`
- **Errors on Multiple Input**: `false`
## Description
Defines a variable named `name` that is accessible in subsequent expressions and has the value of `expr` if present, otherwise the value of the input collection.
## Arguments
- `name`: `String` - Name of the variable
- `expr` (optional): `expression` - Optional expression for the variable's value
## Type Mapping
- `Any-Any`
## Example
```fhirpath
group.select(defineVariable('grp'))
```