---
title: "JavaScript in the export"
slug: "javascript-in-the-export"
abstract: "Computing custom data using JavaScript, and including it in an audience export in Sitecore CDP."
---
# JavaScript in the export

When creating an audience export, you can use JavaScript to compute data in addition to [what's already in the guest profile](https://doc.sitecore.com/cdp/en/users/sitecore-cdp/data-availability-in-sitecore-cdp/available-data-types/guest-data.html "Guest data"). This lets you enrich the data you export from Sitecore CDP.

For example, if the guest's date of birth is in the guest profile, you can [include it in the output](https://doc.sitecore.com/cdp/en/users/sitecore-cdp/audience-export/data-in-the-export.html#UUID-b89e130c-ae01-8831-e80d-ef1c1ff4a1c8_section-idm4545492155870433871423726306 "Including data in the output") as `${guest.dateOfBirth}`, without additional coding required. If the guest's age, however, isn't in the guest profile, you can compute it with JavaScript and then include it in the output.

To use JavaScript in an audience export, you can:

- Enter functions in the **JavaScript** code editor. You can write the code manually, or generate it with the [Code Assistant](https://doc.sitecore.com/cdp/en/users/sitecore-cdp/ai-in-cdp/code-assistant.html "Code Assistant") using natural language. See [code snippets](https://doc.sitecore.com/cdp/en/users/sitecore-cdp/audience-export/code-snippets.html "Code snippets") for example functions.
- [Call a utility function](https://doc.sitecore.com/cdp/en/users/sitecore-cdp/audience-export/javascript-in-the-export.html#UUID-e0fcc0c5-b3e4-cbab-1a1c-81f5c3fee3e4_section-idm4642469535550433964492091815 "Calling utility functions") in a field on the **Output structure** tab.

Here's a video that introduces you to using JavaScript in audience exports:

:::youtube{id="I0EaySNO4os"}

## Computing data using functions

You can use JavaScript functions in an audience export by clicking **Output format** > **Define output** > **JavaScript** code editor. Make sure that you put all the functions inside a single function and that you return a single object:

```javascript
(function () {
  /* first function */
  /* second function */
  /* third function */
  return {} // return a single object
})()

```

In the JavaScript, you can work with data from the guest profile. As you start typing *guest* in the code editor, an autocomplete list of references to the guest data model appears:

![Writing JavaScript and referencing data from the guest data model.](https://doc.sitecore.com/api/markdown-image/cdp/en/users/sitecore-cdp/images/cdp-audience-export-js-1.jpg)

> [!note]
> To prevent errors, we recommend that you log messages to the test log using `console.log()`. You can add logs manually or prompt the [Code Assistant](https://doc.sitecore.com/cdp/en/users/sitecore-cdp/audience-export/code-assistant.html#UUID-4761b59d-a6fb-217e-76e6-25c914dee8ca_section-idm23495970622833 "Understand and refactor code") to create them for you. You'll use the test log when you [test the export](https://doc.sitecore.com/cdp/en/users/sitecore-cdp/audience-export/testing-the-export.html "Testing the export").

### Basic and Advanced mode

You can write JavaScript in Basic or Advanced mode. To select a mode, click **Basic** or **Advanced** at the top of the **Define output** screen.

Here's an overview of the differences between Basic and Advanced mode:

- In Basic mode, the object that the JavaScript returns must be flat with no nesting allowed. The object keys can be strings, numbers, or Boolean values. After writing the function, you use the object key names to [include the data in the output](https://doc.sitecore.com/cdp/en/users/sitecore-cdp/audience-export/javascript-in-the-export.html#UUID-e0fcc0c5-b3e4-cbab-1a1c-81f5c3fee3e4_section-idm4603441978648033871245048397 "Including the computed data in the output") on the **Output structure** tab. The output can be JSON or CSV.
- In Advanced mode, the object that the JavaScript returns can include strings, numbers, Boolean values, and other objects. This means that the object can be nested, allowing you to include more complex data in the output, such as `guest.sessions`. In Advanced mode, there is no need to manually include the computed data in the output. Instead, the JSON output will match the structure of the complete object that the JavaScript returns. CSV is not supported.

#### Examples

::::tabs
:::tab{title="basic-mode"}
##### Basic mode

Example 1. Compute the guest's age

Here's an example JavaScript function in Basic mode. It computes the guest's approximate age by referencing their date of birth in the guest profile:

```javascript
(function () {
    // Calculate age based on a date
    function getAge(date) {
    var today = new Date();
    var birthDate = new Date(date);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
        age--;
    }
    return age;
    }

    // Calculate the guest's age based on their date of birth
    var guestAge = "";
    if (guest.dateOfBirth) {
        guestAge = getAge(guest.dateOfBirth);
    }

    // Return the guest's age in the "age" variable. Then, reference "age" as ${jsResult.age} on the Output structure tab.
    return { age: guestAge }
})()

```

After writing the function, make sure to **Save** your changes.

In the returned object, the key name is `age`. To [include the guest's age in the output](https://doc.sitecore.com/cdp/en/users/sitecore-cdp/audience-export/javascript-in-the-export.html#UUID-e0fcc0c5-b3e4-cbab-1a1c-81f5c3fee3e4_section-idm4603441978648033871245048397 "Including the computed data in the output"), write `${jsResult.age}` in a column on the **Output structure** tab.

:::
:::tab{title="advanced-mode"}
##### Advanced mode

Example 2. Return nested session data

Here's an example JavaScript function in Advanced mode. It returns the guest's session data from the previous 30 days. An audience export with this data helps you find and re-engage inactive guests:

```javascript
(function() {
  load("classpath:moment.js");

  const sessionDataArray = [];
  const tenDaysAgo = moment.utc().subtract(30, "days").format("YYYY-MM-DD");

  if (guest.sessions && guest.sessions.length > 0) {
    for (let index in guest.sessions) {
      const session = guest.sessions[index];
      const sessionDate = moment(session.startedAt).format("YYYY-MM-DD");

      if (sessionDate >= tenDaysAgo) {
        console.log(`Processing session dated: ${sessionDate}`);
        sessionDataArray.push({
          "browserRef": session.browserRef || "",
          "cartType": session.cartType || "",
          "channel": session.channel || "",
          "pointOfSale": session.pointOfSale || "",
          "duration": session.duration || 0,
          "value": session.value || 0,
          "events": session.events || []
        });
        console.log("Session data added");
      }
    }
  }
  console.log("All session data processed.");
  return {
    "sessions": sessionDataArray
  };
})()

```

After writing the function, make sure to **Save** your changes. Then, [test the audience export](https://doc.sitecore.com/cdp/en/users/sitecore-cdp/audience-export/testing-the-export.html "Testing the export") to verify that the JavaScript computation is successful.

:::
::::

#### Including the computed data in the output

If you write JavaScript in Basic mode, you need to include the computed data on the **Output structure** tab, in the **Attribute value** field of a string or number field.

When referencing a key from the object that the JavaScript returns, use the `${jsResult.objectKeyName}` notation. For example, if the JavaScript contains the `age` attribute in the returned object, include that in the **Attribute value** field as `${jsResult.age}`:

![Including the computed data from the JavaScript in the output structure.](https://doc.sitecore.com/api/markdown-image/cdp/en/users/sitecore-cdp/images/cdp-audience-export-js-2.jpg)

After updating the fields, make sure to **Save** your changes. Then, [test the audience export](https://doc.sitecore.com/cdp/en/users/sitecore-cdp/audience-export/testing-the-export.html "Testing the export") to verify that the JavaScript computation is successful.

## Calling utility functions

[Utility functions](https://doc.sitecore.com/cdp/en/users/sitecore-cdp/audience-export/utility-functions.html "Utility functions") help you access data in the guest profile and make data transformations. For example, you can join strings, transform dates, or hash sensitive data so it is securely exported.

You can call these functions in an audience export if you're in Basic mode on the **Define output** screen, by clicking **Output structure** > **Add column**, then entering the utility function in the **Attribute value** field of a string or number field. Make sure to replace the function parameters with values of your choice.

Here's an example of calling the [`${sha256()}`](https://doc.sitecore.com/cdp/en/users/sitecore-cdp/audience-export/utility-functions.html#UUID-125e8b91-06d5-eba1-d97f-4b74c4c00236_section-idm23441412101394 "${sha256(value)}") utility function to securely export a guest's email address:

![cdp-audience-export-js-5.jpg](https://doc.sitecore.com/api/markdown-image/cdp/en/users/sitecore-cdp/images/cdp-audience-export-js-5.jpg)

Or consider a guest profile with the following data extension object:

```json
{
  "dataExtensions": [
    {
      "name": "ext1",
      "values": {
        "MemberCardCategoryRenewalDate": "18/05/2026",
        "MemberCardBalance": 22000,
        "MemberCardType": "shop&miles",
        "MemberCardCategory": "premium",
        "MilesRequiredForMemberCardCategory": 3000
      }
    }
  ]
}

```

You can call *${getDataExtension(guest.dataExtensions, "ext1", "MemberCardCategory", "not-available")}* in the **Attribute value** field to access the value for `MemberCardCategory` and include it in the output.

After updating the fields, make sure to **Save** your changes. Then, [test the audience export](https://doc.sitecore.com/cdp/en/users/sitecore-cdp/audience-export/testing-the-export.html "Testing the export") to verify that the JavaScript computation is successful.