Calculate cart value
Write a Custom JavaScript variable using {{DLV - items}}.
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
SimulationEveryday essentials
Three practice products. Change quantities to vary the input.
- 01FIELD-01, $18.00
- 02FIELD-02, $32.00
- 03FIELD-03, $45.00
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 JavaScriptCtrl / ⌘ + Enter to run. Tab moves to the next control.
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 outputRun 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