This article is produced by scandiweb

scandiweb is the most certified Adobe Commerce (Magento) team globally, being a long-term official Adobe partner specializing in Commerce in EMEA and the Americas. eCommerce has been our core expertise for 20+ years.

Useful JavaScript variables for GTM

Custom Javascript variables are a very useful tool to have in Google Tag
Manager.

This article consist of three parts:

  1. Basics of JavaScript theory, that you will need later on
  2. Useful “building blocks” of code that you could implement in your GTM
  3. Ready to go solutions (Plug-and-play) for:
  • Add to Cart Total Value tracking
  • Remove from Cart Total Value tracking
  • User Lifetime Value tracking
  • Existing Customer tracking
  • Checkout Value tracking
  • Enhanced User ID tracking
  • User Login State tracking

Theory

JavaScript Variables

Variables are containers that you can store values in. You start by declaring a variable with the var keyword, followed by any name you want to call it: var ;

Notes:1. A semicolon at the end of a line indicates where a statement
ends; it is absolutely required!
2. JavaScript is case sensitive —

is a different variable to (you can copy&paste
variable names in order to avoid a mistake)

Variable Types

String
i.e. var pageType = ‘category’

A sequence of text known as a string. To signify that the value is a string, you must enclose it in quote marks.

Number
i.e. var revenue = 10

A number — you can do math operations with it. Numbers don’t have quotes around them.

Boolean
i.e. var userLoggedIn = false

A True/False value. The words true and false are special keywords in JavaScript and don’t need quotes.

Array
i.e. var addToCartProducts = [{id: 1, name : test1}, {id: 2, name : test2}]

A structure that allows you to store multiple values in one single reference.

Commentaries

One line commentaries — //commentaries text

Leave comments in code so others would know what does this code do.

Multiple line commentaries — /Everything in between is a comment. /
This can also be used in order to disable part of the code

We use it from time to time during QA or when running tests.

Operators

Addition “+”

Used to add two numbers together or glue two strings together. Examples:

  • var sum = 4+5; var sum will be equal to 9
  • var sum = ‘4’ + ‘5’; var sum will be equal to “45”

Subtraction, Multiplication, Division “-”, ””, “/” These do what you’d expect them to do in basic math.

Assignment “=”

You’ve seen this already: it assigns a value to a variable.

Comparison Operators

Comparison operators are used in logical statements to determine equality or
difference between variables or values. We will use var x = 5 in all
examples.

Equal value comparison “==”

  • Var x == 8 -> false (equal type, unequal value)
  • var x == 5 -> true (equal type, equal value)
  • var x == ‘5’ -> true (unequal type, equal value)

Equal value AND equal type comparison “===”

  • var x === 5 -> true (equal type, equal value)
  • var x === ‘5’ -> false (unequal type, equal value)

Not equal value comparison “!=”

  • Var x != 8 -> true (equal type, unequal value)

Not equal value OR type comparison “!==”

  • var x !== 5 -> false (equal type, equal value)
  • var x !== ‘5’ -> true (unequal type, equal value)
  • Var x !== 8 -> true (equal type, unequal value)

These do what you’d expect them to do in basic math:

  • Greater than “>”
  • Less than “<”
  • Greater than or equal to “>=”
  • Less than or equal to “<=”

Logical OperatorsGiven that x = 6 and y = 3, logical operator
explanations:

AND “&&”

  • (x < 10 && y > 1) -> true (All conditions must be true)

OR “||”

  • (x < 5 || y > 1) -> true (One of the conditions is true)

NOT “!”

  • !(x===y) -> true (Condition is not true)

Conditional statements

In JavaScript, we have the following conditional statements:

  • Use if to specify a block of code to be executed, if a specified condition
    is true
  • Use else to specify a block of code to be executed, if the same condition
    is false
  • Use else if to specify a new condition to test, if the first condition is
    false
  • Use switch to specify many alternative blocks of code to be executed

The “if” statement

General form:

if (
) {
}

Example:

var userLoginState = {{userLoginState}};
if (userLoginState == ‘LOGGED IN’) {
var userID = {{User ID from dataLayer}}
}

The “else” statement

General form:

 (
) {
} 
 {
}

Example:

var userLoginState = {{userLoginState}};
 (userLoginState == ‘LOGGED IN’) {
var userID = {{User ID from dataLayer}}
} 
 {
var userID = {{User ID from cookie}}
}

The “else if ” statement

General form:

 (
) {
} 
{
}

Example:

var userLoginState = {{userLoginState}};
 (userLoginState == ‘LOGGED IN’) {
var userID = {{User ID from dataLayer}}
} 

 ({{User ID from cookie}} !== undefined) {
var userID = {{User ID from cookie}}
}

The “switch” statement

You won’t really need this one in GTM.

JavaScript for GTM

In GTM we can use JavaScript in two forms:

  1. Within custom HTML tags
  2. Within custom JavaScript variables

Most of the time, you will be using it within custom JavaScript variables,
therefore, today, we will speak about them.

Custom JavaScript variables

The two main things each GTM custom JavaScript variable has:

  1. Function — A JavaScript function is a block of code designed to perform
    a particular task. A JavaScript function is executed when “something”
    invokes it (calls it), in our case it is GTM and it does so constantly.
  2. Return statement — returns a value of the variable

Example:

Useful stuff for custom JavaScript variables

Using GTM variables in custom JavaScript

If you have added a GTM variable — you can use it JavaScript by writing the
variable name in double brackets {{variable name}}. Example:

  • You have created a data layer variable — pageType
  • In order to use it in custom JavaScript variables, you just need to write
    {{pageType}}
  • Then you use it, e.g. “If ({{pageType}} !== ‘category’)”

Accessing array members

Most of the enhanced eCommerce variables are inside an array. In order to access the variable within the array, you need to specify the “path” to the variable.

Example:

  • You have full “ecommerce” array
  • You need to access “option”
  • You write this path:ecommerce.checkout.actionField.option

Example 2:

  • You need to access product name
  • You write this path:ecommerce.checkout.products.0.name

In case you need to access something in [ ] brackets, you need to specify
at which “subarray” you need to take data from
. In this, Example 2, there
could be more than 1 product in the [products] array
.

forEach function

If you need to do an action for EACH member of an array, you can use “forEach” function (seems logical, no?):

Example:

  • You have full “ecommerce” array
  • You need to calculate the value of the cart in the checkout
  • You write the following:{{ecommerce}}.checkout.products.forEach(function(product) {
    var cartValue += parseFloat(product.price) * product.quantity;
    });

In order to calculate the cart total value — you need to sum all the product
revenues. Product revenue equals product price times product quantity. With this expression, you specify JavaScript to do some action for each { } member of [ ] array. In our case, [ ] is a product array and { } is a particular product.

Pushing data to the array

This one you would use if you need to restructure an array. For example, convert the EEC product array to the Facebook contents array.

As an example, we will restructure an Enhanced eCommerce checkout array for the Facebook “intitateCheckout” event needs.

Example:

  • You have full “ecommerce” array
  • You need to have the same data in other structure
  • You do the following:var facebookArray = []; // you specify that it is an array
    {{ecommerce}}.checkout.products.forEach(function(product) {
    facebookArray.push({
    id: products.id,
    quantity: products.quantity,
    item_price: products.price,
    });});

So, on the left, before “:” is a Facebook variable name and on the right
is a corresponding variable from the subarray.

Setting cookies

In GTM, you can create a 1st party cookie, which will store info of your choice
for up to 2 years. Example:

var d = new Date(); //date variable
d.setTime(d.getTime()+1000*60*60*24*365*2); 
var expires = ‘;expires=’+d.toGMTString();
document.cookie = ‘customerLifetimeValue’ + ‘=’ + {{your variable}} + expires + ‘;path=/’;

Putting it all together

Add to Cart Total Value

You could add this one to your “addToCart” EEC event as an event value, so you would know the total add to cart value.

In order to set up this one you will need:

  • Data Layer variable of full ecommerce array, in our case — “ecommerce”function() {
    var addToCartAmount = 0;
    var ecom = {{ecommerce}};
    if (ecom.add && ecom.add.products) {
    ecom.add.products.forEach(function(product) {
    var a = (product.price).replace(/,/g, ‘’);
    addToCartAmount += parseFloat(a) * product.quantity;
    }); };
    return addToCartAmount;
    }

Remove from Cart Total Value

You could add this one to your “removeFromCart” EEC event as an event value, so you would know total add to cart value.

In order to set up this one you will need:

  • Data Layer variable of full ecommerce array, in our case — “ecommerce”function() {
    var removeFromCartTotalAmount = 0;
    var ecom = {{ecommerce}};
    if (ecom.remove && ecom.remove.products) {
    ecom.remove.products.forEach(function(product) {
    var a = (product.price).replace(/,/g, ‘’);
    removeFromCartTotalAmount += parseFloat(a) * product.quantity;
    }); };
    return removeFromCartTotalAmount;
    }

Customer Lifetime Value in Cookie

This one allows you to store your customer’s lifetime value in a cookie. You can use it in order to trigger remarketing tags of your needs. Note: this script
should be added as a custom HTML tag and triggered on the “purchase” event.

For this one you will need to have:

  1. 1st party cookie, in our case — “customerLifeTimeValue” variable name and “customerLifetimeValue” cookie name
  2. Revenue data layer variable — “Order Total”

If User is an Existing Customer

This one requires “Customer Lifetime Value in Cookie” script set up and could be used to trigger remarketing tags and as a custom dimension in Google analytics.

In order to set up this one you will need:

  • Data Layer variable of full ecommerce array, in our case — “ecommerce”function() {
    if (typeof {{customerLifetimeValue in Cookie}} !== ‘undefined’) { return ‘YES’ } else return ‘NO’;}

Checkout Total

It will be useful if you want to know how much money you are losing at each consequent step in the checkout. In order to do so, you will need to add it as a value into your EEC “checkout” event.

In order to set up this one you will need:

  • Data Layer variable of full ecommerce array, in our case — “ecommerce”function() {
    var checkoutValue = 0;
    var ecom = {{ecommerce}};
    if (ecom.checkout && ecom.checkout.products) {
    ecom.checkout.products.forEach(function(product) {
    var a = (product.price).replace(/,/g, ‘’);
    checkoutValue += parseFloat(a) * product.quantity; });
    };
    return checkoutValue;
    }

User ID in the Cookie

It is used for tracking User ID of those visitors, who have logged in some time ago but are not logged in currently.

Basically, this script checks if the User ID in dataLayer is defined and if it
is — the script saves it into the cookie. Afterwards, when User ID in the
dataLayer is not defined — script pulls User ID from the cookie (if there is
one).

In order to set up this one you will need:

  • 1st party cookie for User ID storage, in our case — “User ID in Cookie” variable name and userId as a cookie name
  • Data Layer variable of User ID, in our case — “User ID in dataLayer”function() {
    if ({{User ID in dataLayer}}) {
    var d = new Date(); d.setTime(d.getTime()+1000606024365*2);
    var expires = ‘expires=’+d.toGMTString();
    document.cookie = ‘userId=’ + {{User ID in dataLayer}} + ‘; ‘+expires+’; path=/’;
    return {{User ID in dataLayer}}; }
    else if ({{User ID in Cookie}}) {
    return {{User ID in Cookie}}; }
    return; }

User Login State

We use this script in order to determine if users are logged in at a particular
moment (hit) of their session, you could add this one to your Google Analytics
as a hit-scoped custom metric.

In order to set it up, you will need:

  • Data Layer variable of User ID, in our case — “User ID in dataLayer”function() {
    if ({{User ID in dataLayer}} ) {

    return ‘LOGGED IN’;
    } else {
    return ‘NOT LOGGED IN’;

    }}

There you go, you now know of some basic JavaScript for GTM! We understand it might be hard to get into, but that’s why we’re here — if you have any questions, comments, or would like Scandiweb to help you solve some problems, just shoot us a message at [email protected]!


Need help with your eCommerce?

Get in touch for a free consultation to discuss your business and explore how we can help.

Your request will be processed by

If you enjoyed this post, you may also like