# Variables & Expressions

> Use variables and expressions in Loadster to add dynamic data to your test scripts. Prepopulate variables from a dataset or set them at runtime.

Source: https://loadster.com/manual/variables-and-expressions/

Loadster's variables and expressions allow you to inject dynamic values into your scripts. The `${var}` syntax
described on this page works in [Protocol Bot scripts](https://loadster.com/manual/protocol-scripts/) and
[Browser Bot scripts](https://loadster.com/manual/browser-scripts/) (for Playwright scripts, check out the 
[bot module](https://loadster.com/manual/playwright-scripts/bot/) instead).

Variables and expressions make it possible to do things like:

* Log in with a different username and password each time.
* Capture a CSRF token and reuse it when submitting a secure web form.
* Submit a search with a different search phrase each time.
* Generate a random username for each new registration.

While testing a static website may not require any special variables or expressions, you'll probably need them if you're 
testing a dynamic web application or API.

Variables and expressions work the same in both [Protocol Bot scripts](https://loadster.com/manual/protocol-scripts/) and
[Browser Bot scripts](https://loadster.com/manual/browser-scripts/).

Loadster variables and expressions are denoted by the `${var}` or `${expr()}` syntax. Anything between the `${` and
the `}` is interpreted as a variable or expression.

Variables can have any name you want, as long as it is alphanumeric text with no spaces. Expression functions can be 
any of the predefined functions that Loadster supports.

## Using Expressions in Protocol Bot Scripts

In [Protocol Bot scripts](https://loadster.com/manual/protocol-scripts/), you can use variables throughout your HTTP steps, including:

* URL
* Page resources
* Authentication credentials
* Custom headers
* Request body

### Variables in the URL

Variables can be used in the primary URL for a request, or to append dynamic query string parameters.

_Figure: Using a variable in the URL_


When your script runs, `${BaseURL}` will be substituted with the value of the `BaseURL` variable.

### Variables in page resources

In the example below, a page resource with the `${CoverImage}` variable has been added to the selected HTTP command.

_Figure: Using a variable to load a dynamic page resource_


### Variables in authentication credentials

When setting up authentication for an HTTP step, you can use variables for the username and password.

_Figure: Using variables for HTTP Basic Authentication_


### Variables in custom headers

You can add a request and then insert the variable as the value. This example shows an Authorization header
with `${AuthToken}` as the value.

_Figure: Setting a dynamic request header based on a variable_


### Variables in the request body

In the example below, several values are set as variables in the request body. This makes it possible to submit a
request with different data for each bot. This also works for other body types, not just JSON.

_Figure: Using variables in a request body_


**Important:** When using variables in a request body, the *Interpolate variables* checkbox in the body editor must
be selected. It's on by default for text bodies, but if it gets unchecked, variables are sent as literal strings
instead of being interpolated.

## Using Expressions in Browser Bot Scripts

In Browser Bot scripts, you can use variables or expressions in the DOM selector field or any other primary field.
For example, you could use a variable to supply the text to be entered in a username or password field.

## Scoping of Script Variables

Each bot keeps its own separate variable context. This means that each bot has its own unique value for a given variable
at any given time, and setting a variable for one bot will have no effect on other bots that might also be running
the script.

Also, keep in mind that these Loadster script variables are *different* from JavaScript variables inside a
[code block](https://loadster.com/manual/code-blocks/) or another JavaScript block. To access a script variable from JavaScript, you'll
need to use `bot.getVariable('var')` instead of `${var}`.

## Setting Variables

There are a few ways to set a variable in a Loadster script.

[Dynamic Datasets](https://loadster.com/manual/dynamic-datasets/) allow you to seed data for your test ahead of time. For example, you
might create a data set that contains a list of usernames and passwords. Each bot will then pull a unique value from
the data set and use it when they run the script. Dynamic datasets are a good way to set variables when you know
ahead of time what values you want to use.

[Capturing Rules](https://loadster.com/manual/protocol-scripts/capturing-rules/) let you extract values on the fly from the HTTP 
responses coming back from your site. Capturing is a powerful way to parameterize your scripts when you don't know
the values ahead of time, and where the value might be different each time the script runs. For example, you could 
capture a unique registration code that your application generates after you submit a registration form, and store
it in a variable for later use.

[Code Blocks](https://loadster.com/manual/code-blocks/) can set and retrieve variables programmatically, with `bot.getVariable(name)` and
`bot.setVariable(name, value)`. When you store a script variable in this way, the value is always cast to a string.

## Expression Functions

Expressions are similar to variables in that you can include them in your script in a `${}` section. But instead of
just holding a value, expressions can invoke functions to generate or transform values, and you can even chain 
functions together to apply multiple transformations.

The expression syntax is `${func()}` or `${func(var)}`, where `var` is the name of a variable and `func` is the 
function that is applied.

Loadster supports quite a few functions out of the box.

| function | description |
| --- | --- |
| `urlencode(str)` | Applies URL encoding to the value. |
| `urldecode(str)` | Decodes a URL-encoded value. |
| `base64encode(str)` | Encodes a value as Base64, useful for things like HTTP Basic Authorization headers. |
| `base64decode(str)` | Decodes a Base64-encoded value back to its original form. |
| `jsescape(str)` | Escapes a value so it is safe to use in a JavaScript string. |
| `jsunescape(str)` | Removes JavaScript escape characters from an escaped string, so it can be displayed literally. |
| `htmlescape(str)` | Escapes a string so it can be used safely in HTML, applying escape sequences like `&lt;` and `&gt;`. |
| `htmlunescape(str)` | Removes HTML escape sequences and turns them back to their literal characters. |
| `xmlescape(str)` | Essentially the same as `htmlescape()` but for XML. |
| `xmlunescape(str)` | Essentially the same as `htmlunescape()` but for XML. |
| `uppercase(str)` | Turn all letters in a string to uppercase. |
| `lowercase(str)` | Turn all letters in a string to lowercase. |
| `timestamp()` | Outputs a current Unix timestamp in seconds since the epoch, e.g. *1404432584*. |
| `timestamp("yyyy-MM-dd")` | Outputs a current timestamp, in a format you specify. The format is based on Java’s SimpleDateFormat. |
| `uuid()` | Generates a UUID/GUID, like *1e06863a-6118-426d-bf46-35858c7d797*. |
| `randomalpha(len)` | Generates a random string of alpha characters, of the specified length. |
| `randomnumeric(len)` | Generates a random string of numbers, of the specified length. |
| `randomalphanumeric(len)` | Generates a random string of mixed alpha characters and numbers, of the specified length. |



### Example: Expression to URL encode a query parameter

HTTP requires that special characters in a URL be "URL encoded". Let's say we have a variable called `SearchPhrase` which contains the email address of the current bot. Normally, you could reference it like this:

_Figure: Substituting a literal value in the URL_


However, the email address has an `@` character in it which is not always safe in URLs. To encode it, use the `urlencode()` function:

_Figure: Substituting a safe URL-encoded value in the URL_


The `urlencode()` function in your expression will apply URL encoding to whatever value the `SearchPhrase` variable
currently has. So if your search query is "Transfer Coin", Loadster will substitute the correct URL encoded equivalent of "Transfer%20Coin".

### Example: Expression to escape characters in a JSON request body

Let's say you are testing a RESTful JSON endpoint. The request is supposed to be a POST request with a payload like this:

`{ "fullName": "Buford \"Mad Dog\" Tanner", "age": 26 }`

Instead of submitting the same name each time, you decide to pre-populate a list of names and ages, and then parameterize the request body with variables:

`{ "fullName": "${FullName}", "age": ${Age} }`

But what if your data set contains double quote characters or other characters that are illegal in JSON? To be safe, you should escape them with the jsescape() function:

`{ "fullName": "${jsescape(FullName)}", "age": ${Age} }`

The `jsescape()` function guarantees that the interpolated value is safe to use in a JavaScript or JSON string.

### Example: Expression to uppercase and URL encode a string

There may be occasions (hopefully not too often) that require performing multiple functions on a single value. It is quite straightforward:

`http://www.example.com/users?funkyCapitalizedEmail=${urlencode(uppercase(Email))}`

Operations will be applied in order, starting with the innermost function and proceeding outwards. In the example above, a username like *user@company.com* would become *USER%40COMPANY.COM*.

### Example: Expression to generate a timestamp

Sometimes you need to send a current date or timestamp when making a request.

```text
{
  "name": "Biff Tanner",
  "age": 26,
  "dateCreated": "${timestamp("yyyy-MM-dd'T'HH:mm:ss.S'Z'")}"
}
```


This example formats the timestamp with the current date/time in JavaScript's built-in ISO8601 format. You can specify a different format in the expression (see below).

