# $SCOPE Function

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

- The `$SCOPE` Expression Function is a stand-in for the current column in an object's Column Scope
- It lets one Expression apply to every column in the Scope, instead of naming each `ColumnId`
- It is most useful when Scope is a Data Type, Column Type, or a list of columns

The `$SCOPE` Expression Function refers to **the column currently being evaluated**.

- Some AdapTable objects have [Column Scope](https://www.adaptabletools.com/docs/dev-guide-columns-scope/index.md) covering multiple columns (e.g. all `text` columns, or `ColumnIds` list)
- In this case `$SCOPE` resolves to the Column to which AdapTable is currently applying the rule

That means that instead of repeating and enumerating columns in an Expression, e.g.:
``` 
[github_stars] > 0 AND [github_watchers] > 0 // and more columns here ... 
```

you can write a single Expression that covers all columns more elegantly and succinctly:

```
IS_POSITIVE($SCOPE)
```

It also means that any new columns that get created later but are in Scope will automatically be included.

Always write `$SCOPE` without parentheses - `$SCOPE()` is reported as an error

## When to use `$SCOPE`

`$SCOPE` is useful whenever the object's Scope is **column-agnostic**:

- **Data Types** - e.g. `Scope: { DataTypes: ['number'] }`
- **Column Types** - e.g. `Scope: { ColumnTypes: ['price'] }`
- **Multiple ColumnIds** - e.g. `Scope: { ColumnIds: ['bid', 'ask', 'mid'] }`

It is *not* needed when:

- Scope is a **single named column** - you can just write `[github_stars] > 0`
- Scope is **All** (the whole row) - there is no single "current column" for `$SCOPE` to resolve to

- `$SCOPE` is available in Format Columns, Flashing Cells, Alerts, Column Filters, Plus Minus and Named Queries
- It is not offered where there is no current Column (e.g. a Grid Filter), and an Expression using it there is reported as invalid
- A Named Query which uses `$SCOPE` can only be evaluated when referenced (via `QUERY`) from a Module that has Column Scope

## Using `$SCOPE`

A typical pattern is to pair a Data Type Scope with a `$SCOPE` Expression:

```js [[1, 3, "Scope"], [2, 5, "$SCOPE"]]
FormatColumn: {
  FormatColumns: [{
    Scope: { DataTypes: ['number'] },
    Style: { ForeColor: 'var(--ab-color-palette-19)' },
    Rule: 'IS_POSITIVE($SCOPE)',
  }],
}
```

AdapTable evaluates that rule once per numeric column, substituting `$SCOPE` for that column each time.

**Example: AdapTableQL: $SCOPE Expression Function**

Using $SCOPE so one Expression applies to every column in Scope

- This example uses `$SCOPE` in 2 places, both with a Scope of all `number` columns:
  - A [Format Column](https://www.adaptabletools.com/docs/handbook-column-formatting-conditions/index.md) paints the cell green when `IS_POSITIVE($SCOPE)` and red when `IS_NEGATIVE($SCOPE)`
  - A [Flashing Cell](https://www.adaptabletools.com/docs/handbook-flashing-cell/index.md) flashes when `ANY_CHANGE($SCOPE) AND $SCOPE > 5000`

- Look at `Weekly Issue Change` - positive values are green and negative values are red (in parentheses), using the same Format Columns as every other number column
- Watch numeric cells tick - they flash only when the new value is greater than 5,000

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

```text
src/
  adaptableOptions.ts
  agGridModules.ts      [template]
  columnDefs.ts         [template]
  gridOptions.ts        [template]
  index.ts              [template]
  onAdaptableReady.ts
  rowData.ts            [template]
  styles.css            [template]
  tickingDataHelper.ts  [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} from '@adaptabletools/adaptable';
import {WebFramework} from './rowData';

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: '$SCOPE Expression Function',
  initialState: {
    Dashboard: {
      ModuleButtons: ['FormatColumn', 'FlashingCell'],
    },
    Theme: {CurrentTheme: 'dark'},
    FormatColumn: {
      FormatColumns: [
        {
          Name: 'positive-numbers',
          Scope: {
            DataTypes: ['number'],
          },
          Style: {
            ForeColor: 'var(--ab-color-palette-19)',
            FontWeight: 'Bold',
          },
          Rule: 'IS_POSITIVE($SCOPE)',
        },
        {
          Name: 'negative-numbers',
          Scope: {
            DataTypes: ['number'],
          },
          Style: {
            ForeColor: 'var(--ab-color-palette-30)',
            FontWeight: 'Bold',
          },
          DisplayFormat: {
            Formatter: 'NumberFormatter',
            Options: {
             Parentheses: true,
            },
          },
          Rule: 'IS_NEGATIVE($SCOPE)',
        },
      ],
    },
    FlashingCell: {
      FlashingCellDefinitions: [
        {
          Name: 'flash-large-numbers',
          Scope: {
            DataTypes: ['number'],
          },
          Rule: 'ANY_CHANGE($SCOPE) AND $SCOPE > 5000',
        },
      ],
    },
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          Name: 'Standard Layout',
          TableColumns: [
            'name',
            'language',
            'github_stars',
            'github_watchers',
            'week_issue_change',
            'open_issues_count',
            'open_pr_count',
          ],
          AutoSizeColumns: true,
        },
      ],
    },
  },
};
```

**`src/onAdaptableReady.ts`**

```ts
import {AdaptableReadyInfo} from '@adaptabletools/adaptable';
import {tickNumericData} from './tickingDataHelper';

export const onAdaptableReady = ({adaptableApi}: AdaptableReadyInfo) => {
  tickNumericData(adaptableApi, 300, [
    'github_stars',
    'github_watchers',
    'week_issue_change',
  ]);
};
```

`$SCOPE` is also commonly used in:

- [Data Change Alerts](https://www.adaptabletools.com/docs/handbook-alerting-data-change/index.md) - e.g. `IS_BLANK($SCOPE)` for all text columns
- [Validation Alerts](https://www.adaptabletools.com/docs/handbook-validating-client/index.md) - e.g. `STARTS_WITH($SCOPE, "A")` for all text columns in Scope (validation is an Alert with Prevent Edit, not a separate Module)

- See [Column Scope](https://www.adaptabletools.com/docs/dev-guide-columns-scope/index.md) for how Scope is defined
- See [Conditional Styling](https://www.adaptabletools.com/docs/handbook-column-formatting-conditions/index.md) for the most common `$SCOPE` use case
