Skip to content
HomeTraining

Calculate cart value

Write a Custom JavaScript variable using {{DLV - items}}.

All exercisesSaved on this device

Your task

Return the sum of price × quantity for {{DLV - items}}. Convert numeric strings, default missing quantity to 1, skip invalid prices and return 0 for missing or empty items.

  • Returns a number
  • Handles multiple quantities and numeric strings
  • Preserves zero quantity and handles missing fields

Practice site

Simulation
Field Supply

Everyday essentials

3

Three practice products. Change quantities to vary the input.

  • 01
    FIELD-01, $18.00
    2
  • 02
    FIELD-02, $32.00
    1
  • 03
    FIELD-03, $45.00
    0

Cart 3

Items before discount
$68.00
Total
$68.00
DLV - items
{
  "ecommerce.items": [
    {
      "item_id": "FIELD-01",
      "item_name": "Notebook",
      "item_category": "Stationery",
      "price": 18,
      "quantity": 2
    },
    {
      "item_id": "FIELD-02",
      "item_name": "Water bottle",
      "item_category": "Accessories",
      "price": 32,
      "quantity": 1
    }
  ]
}

Run your solution to enable actions.

Your solution

Custom JavaScript
function() {
var items = {{DLV - items}} || [];
// Return the sum of price × quantity as a number.
return 0;
}

Ctrl / ⌘ + Enter to run. Tab moves to the next control.

Run to apply your changes.
Hints and explanation

A Custom JavaScript variable is a function expression that returns a value. {{DLV - items}} is resolved before the function runs. It represents ecommerce.items in this task.

    Result

    Local output

    Run the solution, then try an action on the practice site.

    What this lab supports

    The lab supports dataLayer.push, Data Layer / Constant / Event / Custom JavaScript variables, Custom Event conditions and a local GA4 Event output. Custom HTML supports one inline script and the small DOM described in that exercise. No container, Preview connection, consent engine, templates, external scripts or GA4 delivery are included.

    Messages are processed in order. Objects merge, arrays replace previous arrays, and null clears a value. Dotted paths read the state at that event. This is a documented subset, not full GTM Data Layer Variable v2 behavior. {{Variable}} references work outside strings and comments; references inside template literals and regular expressions are unsupported.

    The JSON export is a lab project, not a GTM container. To transfer a solution, create the corresponding variables, trigger and tag in GTM and test them on your own site. Student code has no access to this site’s cookies, storage, network or production dataLayer.

    Google: the data layer