# VAR Function

Canonical page: https://www.adaptabletools.com/docs/adaptable-ql-expression-advanced-var-function

- The `VAR` function in AdapTableQL enables developers to supply bespoke, custom values
- These can then be referenced, and evaluated, in other Expressions

The `VAR` Expression Function allows developers to provide custom values which can be used in Expressions.

The return value of the `VAR` can be either

- a 'hard-coded' value (string, number, boolean or Date)
- a function that returns a value

The VAR values are provided at design-time via the `queryVariables` property in [Expression Options](https://www.adaptabletools.com/docs/technical-reference-expression/index.md).

### `queryVariables`

Query Variables which can be referenced in Expressions via VAR

Property which allow values to be attached to variables so that a single value can easily be expressed multiple times within a query, or quickly changed to affect the results of a query.

Variables are evaluated synchronously with each expression evaluation.

The definition of the property is:

```ts
queryVariables?: QueryVariable[];

interface QueryVariable {
  name: string;
  value:
    | string | number | boolean | Date
    | ((context: QueryVariableContext) => string | number | boolean | Date);
  description?: string;
}
```

Each Query Variable has:

- `name` - used to reference it in an Expression, e.g. `VAR('VAT')`
- `value` - either a value or a function that returns a value
- `description` - optional text shown in the Expression Editor

So, for example, a VAR which returns the VAT rate can be provided in 2 ways.

Either as a hard-coded value:

```ts {3,4}
// Provide VAT as a hard-coded value
expressionOptions: {
  queryVariables: [
    { name: 'VAT', value: 1.2, description: 'Standard VAT rate' },
  ],
};
```

Or using a function which receives a `QueryVariableContext` object and returns a value.

The [`QueryVariableContext`](https://www.adaptabletools.com/docs/reference/queryvariablecontext.md) contains the custom args required by the VAR (e.g. `[country]` in `VAR('VAT', [country])`).

```ts {3,4,5}
// Provide VAT using a function (in the real world this will call server logic)
expressionOptions: {
  queryVariables: [
    {
      name: 'VAT',
      value: (context: QueryVariableContext) => {
        const country = context.args?.[0];
        switch (country) {
          case 'US':
            return 1;
          case 'Japan':
            return 1.1;
          case 'Germany':
            return 1.19;
          case 'UK':
            return 1.2;
        }
        return 1;
      },
    },
  ],
};
```

**Example: AdapTableQL: VAR Expression Function**

Using VAR to provide placeholders and variables

- This Example demonstrates how to use the `VAR` Expression Function
- In [Expression Options](https://www.adaptabletools.com/docs/technical-reference-expression/index.md) we define 3 `VAR` Expressions (all of which are then used in Adaptable Objects):
  - `EMISSION_DATE` - has a hard-coded value of 1 Jan 2014 - and then used in a [Format Column Condition](https://www.adaptabletools.com/docs/handbook-column-formatting-conditions/index.md)
  - `VAT` - a function that returns a number based on the Country param it receives - used to create the `Full Price` [Calculated Column](https://www.adaptabletools.com/docs/handbook-calculated-column/index.md)
  - `BEST_SELLER` - has a mock server returned value of "Corolla" - and then used in a [Format Column Condition](https://www.adaptabletools.com/docs/handbook-column-formatting-conditions/index.md) and a [Data Change Alert](https://www.adaptabletools.com/docs/handbook-alerting-data-change/index.md)
- We have also created a [Named Query](https://www.adaptabletools.com/docs/handbook-named-queries/index.md) called 'Good Performance' which uses the first 2 VAR Expressions

- Change the Price for "Corolla" and note the Alert that fires
- Select and run the "Good Performance" Query from the Grid Filter Toolbar and see both VAR Expressions be used

Demo project (Vanilla); the files without a marker are shown below:

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts
  gridOptions.ts
  index.ts             [template]
  onAdaptableReady.ts  [template]
  rowData.ts
  styles.css           [template]
index.html             [template]
package.json           [template]
tsconfig.json          [template]
```

Files marked `[template]` are the same in every demo; see the [demo template](https://www.adaptabletools.com/llms/demo-template.md#vanilla).

**`src/adaptableOptions.ts`**

```ts
import {
  AdaptableOptions,
  QueryVariableContext,
} from '@adaptabletools/adaptable';
import {Car} from './rowData';

export const adaptableOptions: AdaptableOptions<Car> = {
  primaryKey: 'model',
  adaptableId: 'VAR Expression Functions',
  expressionOptions: {
    queryVariables: [
      {
        name: 'BEST_SELLER',
        value: () => {
          return 'Corolla'; // would normally fetch from server
        },
        description: 'The current best selling model',
      },
      {
        name: 'EMISSION_DATE',
        value: new Date(2014, 0, 1),
        description: 'Date when new emission rules came into force',
      },
      {
        name: 'VAT',
        value: (context: QueryVariableContext) => {
          const country = context.args?.[0];
          switch (country) {
            case 'US':
              return 1;
            case 'Japan':
              return 1.1;
            case 'Germany':
              return 1.19;
          }
          return 1;
        },
        description: 'VAT rate for the given Country',
      },
    ],
  },
  initialState: {
    Dashboard: {
      ModuleButtons: ['FormatColumn'],
      PinnedToolbars: ['GridFilter'],
    },
    Theme: {CurrentTheme: 'dark'},
    NamedQuery: {
      NamedQueries: [
        {
          Name: 'Good Performance',
          Expression:
            'VAR("VAT",[country]) > 1 AND DIFF_YEARS(VAR("EMISSION_DATE") , [productionDate])  < 1',
        },
      ],
    },
    Alert: {
      AlertDefinitions: [
        {
          Name: 'alert-best-seller',
          Scope: {
            All: true,
          },
          Rule: '[model] = VAR("BEST_SELLER")',
          MessageType: 'Warning',
          MessageText: 'Updating the current Best Seller!',
          AlertProperties: {
            DisplayNotification: true,
          },
        },
      ],
    },
    CalculatedColumn: {
      CalculatedColumns: [
        {
          ColumnId: 'full_price',
          FriendlyName: 'Full Price',
          Expression: "[price] * VAR('VAT',[country])",
          CalculatedColumnSettings: {
            DataType: 'number',
            Resizable: true,
          },
        },
      ],
    },
    FormatColumn: {
      FormatColumns: [
        {
          Name: 'style-emissions',
          Style: {
            BackColor: '#b3e5fc',
            ForeColor: 'var(--ab-color-palette-13)',
          },
          Scope: {
            All: true,
          },
          Rule: 'VAR("EMISSION_DATE") > [productionDate]',
        },
        {
          Name: 'style-best-seller',
          Style: {
            FontSize: 'Large',
            FontWeight: 'Bold',
            FontStyle: 'Italic',
          },
          Scope: {
            ColumnIds: ['model'],
          },
          Rule: 'VAR("BEST_SELLER") = [model]',
        },
        {
          Name: 'formatColumn-price-full_price',
          Scope: {
            ColumnIds: ['price', 'full_price'],
          },
          DisplayFormat: {
            Formatter: 'NumberFormatter',
            Options: {
              Prefix: '$',
              FractionDigits: 0,
            },
          },
        },
        {
          Name: 'formatColumn-milesToGallon',
          Scope: {
            ColumnIds: ['milesToGallon'],
          },
          DisplayFormat: {
            Formatter: 'NumberFormatter',
            Options: {
              FractionDigits: 2,
            },
          },
        },
        {
          Name: 'formatColumn-productionDate',
          Scope: {
            ColumnIds: ['productionDate'],
          },
          DisplayFormat: {
            Formatter: 'DateFormatter',
            Options: {
              Pattern: 'yyyy/MM/dd',
            },
          },
        },
      ],
    },

    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          Name: 'Standard Layout',
          TableColumns: [
            'make',
            'model',
            'price',
            'full_price',
            'productionDate',
            'available',
            'milesToGallon',
            'country',
          ],
          AutoSizeColumns: true,
        },
      ],
    },
  },
};
```

**`src/gridOptions.ts`**

```ts
import {GridOptions, themeBalham} from 'ag-grid-enterprise';

import {columnDefs} from './columnDefs';
import {Car, rowData} from './rowData';

export const gridOptions: GridOptions<Car> = {
  theme: themeBalham,
  defaultColDef: {
    resizable: true,
    sortable: true,
    editable: true,
    filter: true,
    floatingFilter: true,
  },
  columnDefs: columnDefs,
  rowData: rowData,
  sideBar: true,
  suppressMenuHide: true,
  cellSelection: true,
  statusBar: {
    statusPanels: [
      {statusPanel: 'agTotalRowCountComponent', align: 'left'},
      {statusPanel: 'agFilteredRowCountComponent'},
      {
        key: 'Center Panel',
        statusPanel: 'AdaptableStatusPanel',
        align: 'center',
      },
    ],
  },
};
```

**`src/columnDefs.ts`**

```ts
import {ColDef} from 'ag-grid-enterprise';
import {Car} from './rowData';

export const columnDefs: ColDef<Car>[] = [
  {
    headerName: 'Make',
    field: 'make',
    filter: true,
    editable: false,
    enableRowGroup: true,
    enablePivot: true,
    cellDataType: 'text',
  },
  {
    headerName: 'Model',
    field: 'model',
    filter: true,
    editable: false,
    cellDataType: 'text',
  },
  {
    headerName: 'Price',
    field: 'price',
    filter: true,
    editable: true,
    cellDataType: 'number',
  },
  {
    headerName: 'Miles To Gallon',
    field: 'milesToGallon',
    filter: true,
    editable: false,
    cellDataType: 'number',
  },
  {
    headerName: 'Produced',
    field: 'productionDate',
    filter: true,
    editable: false,
    cellDataType: 'date',
  },
  {
    headerName: 'Available',
    field: 'available',
    filter: true,
    editable: true,
    cellDataType: 'boolean',
  },

  {
    headerName: 'Country',
    field: 'country',
    filter: true,
    editable: false,
    cellDataType: 'text',
  },
];
```

**`src/rowData.ts`**

```ts
export interface Car {
  make: string;
  model: string;
  price: number;
  productionDate: Date;
  available: boolean;
  milesToGallon: number;
  country: string;
}

export const rowData: Car[] = [
  {
    make: 'Toyota',
    model: 'Camry',
    price: 35000,
    productionDate: new Date(2017, 11, 4),
    available: true,
    milesToGallon: 21.345676,
    country: 'Japan',
  },
  {
    make: 'Toyota',
    model: 'Yaris',
    price: 40000,
    productionDate: new Date(2013, 1, 15),
    available: true,
    milesToGallon: 29.32432423,
    country: 'Japan',
  },
  {
    make: 'Toyota',
    model: 'Corolla',
    price: 28000,
    productionDate: new Date(2017, 6, 9),
    available: false,
    milesToGallon: 32.9032523473287,
    country: 'Japan',
  },
  {
    make: 'Ford',
    model: 'Mondeo',
    price: 32000,
    productionDate: new Date(2009, 10, 2),
    available: true,
    milesToGallon: 28.247893473289,
    country: 'US',
  },
  {
    make: 'Ford',
    model: 'Fiesta',
    price: 35000,
    productionDate: new Date(2018, 8, 12),
    available: false,
    milesToGallon: 34.0001,
    country: 'US',
  },
  {
    make: 'Ford',
    model: 'Focus',
    price: 26750,
    productionDate: new Date(2017, 3, 3),
    available: false,
    milesToGallon: 31.2432432423,
    country: 'US',
  },
  {
    make: 'Ford',
    model: 'Galaxy',
    price: 41000,
    productionDate: new Date(2015, 4, 14),
    available: false,
    milesToGallon: 29.29432404,
    country: 'US',
  },
  {
    make: 'Porsche',
    model: 'Boxter',
    price: 72500,
    productionDate: new Date(2016, 1, 28),
    available: true,
    milesToGallon: 32.29580292,
    country: 'Germany',
  },
  {
    make: 'Porsche',
    model: 'Mission',
    price: 81000,
    productionDate: new Date(2008, 10, 7),
    available: false,
    milesToGallon: 35.7822957,
    country: 'Germany',
  },
  {
    make: 'Mitsubbishi',
    model: 'Outlander',
    price: 97800,
    productionDate: new Date(2017, 11, 14),
    available: true,
    milesToGallon: 19.224309,
    country: 'Japan',
  },
];
```
