# Function thinklet

The Function thinklet enables custom data transformations and computations using JavaScript. While built-in thinklets handle most tasks, the Function thinklet provides flexibility for complex data manipulation and workflow logic.

### How it works

Add JavaScript code to the Function thinklet to transform data, generate insights, and automate workflow decisions. Functions are executed in batches to ensure scalability across large environments. As a result, execution is not guaranteed to start instantly. The Function Thinklet should therefore not be used for time-sensitive operations

### Use cases

Use the Function thinklet for:

* **Data transformation**: Convert values, format data, and compute new metrics.
* **Time calculations**: Determine time differences and track durations.
* **Decision automation**: Use computed outputs to drive conditional workflow logic.

### Restrictions

To ensure performance, security, and predictability, the Function thinklet enforces the following rules:

* The Function thinklet runs in a secure and isolated environment. It cannot make HTTP requests, access external services or APIs, or interact with any system outside the workflow. This restriction guarantees that execution remains safe, consistent, and compliant with security policies.
* Function thinklets must complete all logic within 5 seconds. Scripts that exceed this time limit will be automatically terminated. As a result, introducing artificial delays or using the Function thinklet to pause workflow execution is not supported.

Use the Function thinklet exclusively for fast, local data processing and decision-making. For any advanced use cases involving delays or external interactions, consider using purpose-built thinklets.

<figure><img src="/files/yx8cziI7CIRE5Pkw6Evz" alt=""><figcaption></figcaption></figure>

## Configuring the Function thinklet

{% hint style="info" %}
[Generate with AI](#generating-javascript-with-ai-for-function-thinklets) the JavaScript that defines the Function thinklet. For best results, structure your AI prompt according to the examples on this page.
{% endhint %}

Simplify third-party integrations by converting raw data into meaningful formats to, for example, calculate the number of days between two dates, without using workarounds or external tools.

<div align="left"><figure><img src="/files/lluL3xAf0bhvAe2rA1EQ" alt="" width="375"><figcaption></figcaption></figure></div>

* **Name**: Enter a unique name for the Function thinklet.
* **ID**: The system generates the ID automatically based on the name.
* **Description (optional)**: Describe the purpose of the thinklet and what it does. This information is useful for others using the workflow who may not be familiar with it.
* **Parameters**: Select **Add parameter** to configure up to 5 thinklet parameters that also become input parameters for the function logic.
  * **ID**: Define the input parameter ID. Validation logic allows only the characters that are supported by JavaScript.
  * **Value**: Set the corresponding parameter value—database value, output of another thinklet, global parameter, or custom value.
    * You can select [manual custom fields](/platform/user-guide/administration/content-management/custom-fields-management.md#customfieldsmanagement-choosingmanualcustomfieldtypemanual)—`user` or `device` attributes—as parameter values in thinklets to use environment-specific data as input.
* **Outputs**: Select **Add outputs** to configure up to 5 outputs for the function.
  * **Name**: Enter a unique name for the desired output.
  * **ID**: The system generates the ID automatically based on the name.
* **JavaScript**: Write a JavaScript code that defines the function's logic based on the input parameters. The script should also define any outputs that contain the IDs of defined Outputs.
  * You can **Generate with AI** the JavaScript for the **Function** thinklet.

### Generating JavaScript with AI for Function thinklets

{% hint style="info" %}
The system displays the ✦ sparkles icon to indicate AI-generated content or insights. AI is evolving rapidly and delivering great insights, but it can still make mistakes. Nexthink recommends validating your results to ensure accuracy and support informed decision-making. Refer to the [Global AI Hub](https://docs.nexthink.com/legal/global-ai-hub) documentation for more information.
{% endhint %}

To generate the **JavaScript** that defines the workflow **Function** thinklet with AI:

1. Click the **Generate with AI** button.
2. Insert your **Prompt** request describing input parameters, desired outputs, and required transformations. Refer to the [prompt examples](#javascript-examples-for-function-thinklets-prompts-and-codes) for more details.
3. Examine the **Explanation** and ensure the generated **Code** meets your logic requirements. If logic updates are necessary, modify the prompt and regenerate the function.

The AI code generator follows the JavaScript **code structure and syntax** for Function thinklets:

<details>

<summary>JavaScript <strong>code structure and syntax</strong> for Function thinklets</summary>

Follow these syntax rules to ensure your JavaScript works correctly and remains easy to debug:

* Define access input parameters in the configuration using `inputs.parameter_ID`
* Assign output values with the syntax `outputs.output_ID`
* Include useful information in the Workflow execution timeline for troubleshooting by using `nxLogger.log()`

```javascript
// Access input parameters
const param1 = inputs.parameter_ID_1;
const param2 = inputs.parameter_ID_2;
// ...
const paramN = inputs.parameter_ID_5; // Up to 5 parameters

// Logic for transformations

outputs.output_1 = /* your logic here */;
outputs.output_2 = /* your logic here */;
// ...
outputs.output_5 = /* your logic here */;

// Output any results for troubleshooting
nxLogger.log("Name the output" + output_1);
```

</details>

<details>

<summary><strong>Unsupported</strong> functions and objects for Function thinklets</summary>

The following global functions and objects are not supported:

* `setTimeout`
* `setInterval`
* `setImmediate`
* `clearTimeout`
* `clearInterval`
* `clearImmediate`
* `process`
* `require`
* `Buffer`
* `console`
* `process.nextTick`

</details>

<figure><img src="/files/LVcqmhsDkVzsGft4etHh" alt=""><figcaption></figcaption></figure>

### JavaScript Examples for Function thinklets: prompts and codes

Find below examples of JavaScript AI prompting and coding:

<details>

<summary>Example of a Prompt to generate JavaScript with AI</summary>

*Compute the number of days left for the warranty to expire based on the warranty end date. If already expired, output 0.*

</details>

<details>

<summary>Use case: Password expiration checker within a Function thinklet</summary>

This code example shows how to implement a password expiration checker within a Function thinklet.

```javascript
// Access input parameter
const lastUpdate = inputs.last_update_date;
 
// Define password validity period (90 days)
const validityDays = 90;
const expirationDate = new Date(lastUpdate);
expirationDate.setDate(expirationDate.getDate() + validityDays);
 
// Get current date
const now = new Date();
 
// Calculate days left
const timeDiff = expirationDate - now;
const daysLeft = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));
 
// Set outputs 
outputs.days_left = daysLeft;                  // Days_to_change_password
outputs.if_expired = daysLeft <= 0;             // Already_expired
 
// Output intermediate results for troubleshooting
nxLogger.log("Days left: " + daysLeft);
nxLogger.log("Need to notify: " + outputs.output_2);

```

</details>


---

# 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.nexthink.com/platform/user-guide/workflows/creating-workflows/configuring-thinklets/function-thinklet.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.
