# function

Functions allow you to create short, reusable scripts that can be called from any of your other scripts. They are useful for encapsulating logic you use in multiple places - API calls, data transformations, calculations, and more.

To create a function, select the `Add new function script` button.

### Syntax

```liquid
{% function "function_handle", param1:value1, param2:value2 as result %}
```

* `"function_handle"` — the handle (or ID) of the function script to call.
* `param1:value1, param2:value2` — named parameters. Each becomes a variable inside the function.
* `as result` — captures the function's return value into a variable.

### Parameters

Named parameters let you pass values directly into the function scope. Each `key:value` pair becomes a variable accessible inside the function code.

Values can be variables, string literals, or any Liquid expression:

```liquid
{% assign user_email = "support@code57.pl" %}

{% function "send_email", email:user_email, subject:"Welcome!" as email_result %}
```

Inside the function, `email` and `subject` are available as regular variables.

You can pass as many parameters as needed:

```liquid
{% comment %}Inside webhook orders/paid script{% endcomment %}
{% assign order = payload %}
{% function "create_order_note", order_id:order.id, message:"Note text", priority:"high", notify:true as note_result %}
{% log note_result %}
```

### Return values

Functions return a value using the `return` tag. The returned value is captured by the `as` clause.

**Function code** (handle: `add_numbers`):

```liquid
{% comment %}Inside function script{% endcomment %}
{% assign sum = a | plus: b %}
{% return sum %}
```

**Calling the function:**

```liquid
{% function "add_numbers", a:5, b:3 as sum_result %}
{% log "This is result: " | append: sum_result %}
```

Output: `The sum is: 8`

The `as sum_result` clause saves the return value so you can use it later in your script — log it, pass it to another function, or use it in conditions:

```liquid
{% function "add_numbers", a:5, b:3 as sum_result %}
{% if sum_result > 5 %}
  {% log "Sum is greater than 5" %}
{% endif %}
```

#### Without `as`

The `as variable` clause is optional. If omitted, the function's return value is written directly to the output:

```liquid
{% function "add_numbers", a:5, b:3 %}
```

This also outputs `8`, but you cannot reference the result later in your script.

### Example: Send metrics to Klaviyo

**Function code** (handle: `send_metric_to_klaviyo`):

```liquid
{% json body %}
{
  "data": {
    "type": "event",
    "attributes": {
      "properties": {
        "membership": {{ property | default: "" | json }}
      },
      "metric": {
        "data": {
          "type": "metric",
          "attributes": {
            "name": {{ metric | default: "" | json }}
          }
        }
      },
      "profile": {
        "data": {
          "type": "profile",
          "attributes": {
            "email": {{ email | default: "" | json }}
          }
        }
      }
    }
  }
}
{% endjson %}

{% json request_options %}
{
  "url": "https://a.klaviyo.com/client/events/?company_id={{KLAVIYO_TOKEN}}",
  "method": "POST",
  "headers": {
    "Content-Type": "application/json",
    "Accept": "application/json",
    "Revision": "2024-05-15"
  },
  "body": {{ body | json }}
}
{% endjson %}
{% http url:request_options.url, method:request_options.method, body:request_options.body, headers:request_options.headers as response %}
{% return response %}
```

Notice that `email`, `property`, and `metric` are used directly as variables — they are injected into the function scope when the function is called.

**Calling the function from another script:**

```liquid
{% assign user_email = "support@code57.pl" %}
{% assign membership_level = "GOLD" %}

{% function "send_metric_to_klaviyo", email:user_email, property:membership_level, metric:"MEMBERSHIP UPDATE" as fn_result %}

{% log fn_result %}
```

After execution, `fn_result` contains the result of the HTTP call made inside `send_metric_to_klaviyo`.

### Example: Reusable GraphQL helper

**Function code** (handle: `get_product_title`):

```liquid
{% capture query %}
  query { product(id: "{{ product_id }}") { title } }
{% endcapture %}
{% graphql query:query as gql_result %}
{% return gql_result.data.product.title %}
```

**Calling the function:**

```liquid
{% function "get_product_title", product_id:"gid://shopify/Product/123456" as title %}
{% log title %}
```

### Example: Calling a function inside a loop

Functions are especially useful inside loops where you need to perform the same operation for each item:

```liquid
{% for item in order.line_items %}
  {% function "check_inventory", variant_id:item.variant_id, quantity:item.quantity as stock_status %}
  {% if stock_status.available == false %}
    {% log "Out of stock: " | append: item.title %}
  {% endif %}
{% endfor %}
```

### Legacy format: JSON payload

The old format using a single JSON payload variable is still supported. All keys from the payload object are spread into the function scope.

```liquid
{% json fn_input %}
{
  "email": "support@code57.pl",
  "property": "GOLD",
  "metric": "MEMBERSHIP UPDATE"
}
{% endjson %}

{% function "send_metric_to_klaviyo", fn_input as fn_result %}

{% log fn_result %}
```

> **Note:** Named parameters and the JSON payload format cannot be mixed in a single call. Use one or the other.

### Limitations

* **No nested function calls** — you cannot call a function from inside another function.
* **Task variables are not available** inside functions. Pass any values you need as parameters.
* **Global variables are accessible** inside functions.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.datajet-app.com/liquid/tags/function.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
