
May 2, 2024
JavaScript for Google Tag Manager: 5 topics to learn
You might not know it, but when using Google Tag Manager, you’re essentially configuring JavaScript code that is looking for website interactions and fires tracking codes. Google Tag Manager just provides an easy UI to do this, so no coding experience is needed!
However, the more you work with Google Tag Manager, the more you will find the need to understand and use JavaScript to further your analytics. Using JavaScript in either custom HTML tags, JavaScript variables, or Custom templates allows you more flexibility to pull through information on how users interact with your site.
If you’re new to programming, learning JavaScript might seem daunting. But hey, we have to start somewhere, right? This tutorial will help make things more manageable by covering five key topics on JavaScript for Google Tag Manager. Let’s dive into it!

Video tutorial
If you prefer video content, here’s a tutorial from my Youtube channel.
What is JavaScript?
Before we jump into the coding aspect of JavaScript, it may be helpful to have some background on what JavaScript is. There is no need for a hoodie or Matrix-like code scrolling, just a keyboard and an eagerness to learn!
You can imagine JavaScript as the man (or woman) behind the curtain of a website; it brings everything to life. It works alongside HTML and CSS to create interactive and dynamically changing websites. HTML is responsible for the content and its structure, CSS adds the style, and JavaScript makes the elements interactive.
In Google Tag Manager, you will use JavaScript to add custom scripts to your website without directly modifying the site’s code.
To explore JavaScript beyond what we cover in this tutorial, consider completing the W3School’s free JavaScript training.
Basic JavaScript Syntax
While human languages rely on grammar to make sense, programming languages rely on syntax. These are the set of rules that define how you need to write your code for it to be understood and executed. Programming languages can also have different versions, which may have different syntaxes.
The current version of JavaScript is ECMASCRIPT6 (EC6), but Google Tag Manager mainly supports ECMASCRIPT5 (EC5). While GTM supports EC6 in Custom Tag Templates, it only supports EC5 in custom HTML tags or custom JavaScript variables.
There are a few notable differences in the syntax between the two versions.
For example, when EC6 launched, it brought with it the arrow function (=>). Without getting too much into the details, the critical thing to remember is that this function doesn’t work in EC5. Therefore, it won’t work in custom HTML tags or custom JavaScript variables in GTM.
Google Tag Manager will show an error if you use the incorrect syntax or invalid functions in your container when you go to Preview or Publish.
Assigning Variables in JavaScript
In programming, variables assign a name to a value or object, allowing access to the data by referencing the variable. The syntax for assigning variables differs between EC5 and EC6.
// ECMASCRIPT5 syntax var x = 2; var y = 3; var z = x + y; // z is now 5 // ECMASCRIPT6 syntax const x = 2; const y = 3; let z = x + y;
Once you start building out code, it’s helpful to declare a variable rather than just use the value (e.g. using x instead of 2). This way, if you need to change the value, rather than replacing it everywhere in your code, you just need to update one variable.

5 JavaScript Topics to learn
Now that we’ve gotten some of the essentials out of the way, we’re ready for the key topics. With the end goal of using these skills in Google Tag Manager, you don’t need to be a computer hacker to get there. Let’s start with the five topics before getting ahead of ourselves.
Topic 1: Data types & structural types
Data Types in JavaScript
In programming, the data type tells the computer what information the variable stores and defines how it processes and manipulates it. Some common data types in JavaScript include strings, numbers, boolean, and objects.
A string is a series of characters enclosed by quotation marks. In other words, a text.
var clothingBrand = 'Nike';
A number is, as expected, a numeric value.
var price = 15;
A boolean can only have one of two values: true or false. It is used for logical operations and decision-making in code.
var isOnSale = true; var isOnClearance = false;
Data Structures
If data types are the ingredients, data structures are the recipes that combine the ingredients. Structural types store variables of different data types for efficient access. Common structural types are arrays and objects.
An array allows you to hold multiple values in a single variable. Square brackets define an array and the values within are accessed using an index. In JavaScript, indexing begins at 0.
var clothingCategories = ['shoes', 't-shirts', 'pants']; var firstElement = myArray[0]; // returns 'shoes'// arrays can hold multiple data types var dataTypes = ['string', 1, true, [1, 2, 3]];
A solid understanding of data structures will help unravel the mystery of the dataLayer. You or your developers can push information into the array (like custom events). You can also pull data from the dataLayer with Google Tag Manager, which you can learn more about here.
Similarly, an object can hold multiple values of different data types. An object contains key-value pairs enclosed by curly brackets.
var objectExample = {key: value}; // Example var itemDetails = { materialComposition: { 'cotton': 70, 'linen': 30 }, price: 30, onSale: false, searchTags: ['t-shirt', 'women', 'tops'] };
Topic 2: Functions & scope
JavaScript Functions
A JavaScript function is a block of code that performs a purposeful action. It takes in an input, performs an action on the input and returns the desired output. You can think of it as a factory machine that takes in one or more pieces of material and outputs a finished product.
Functions are helpful since you can reuse them throughout your code. In the example below, the function takes in the price of an item and the tax (as a decimal) and returns the price after tax.
function priceAfterTax(price, tax) { return price * (1 + tax); };
When creating custom JavaScript variables in GTM, you will use anonymous functions, meaning you do not name them. The example below comes from the tutorial on how to track Vimeo players with GTM and GA4.
function () { for (var e = document.getElementsByTagName("iframe"), x=0; x < e.length; x++) { if (/^https?:\/\/player.vimeo.com/.test(e[x].src)) { return true; } } return false; }
If you look at the code in the Vimeo tutorial, you can see that it contains multiple functions that work together to achieve the end goal of dispatching a Data Layer event.
Conditional statements (or if statements) will enable us to define unique actions that depend on the input meeting certain conditions. They are often used in functions to return different outputs depending on the input.
In the below code, depending on the price of an item, the function returns a boolean for whether shipping will be free.
function freeShipping(price) { if (price < 100) { return false; } else { return true; } };
Additionally, you can read more about the try…catch statement, which allows you to test for errors in your code.
JavaScript Scopes
Scope defines the accessibility of a variable, object, and function from different parts of the code. There are two main scopes for EC5: global and function (a.k.a. local).
Global scope is defined outside of a function so that you can access it throughout the code. Function scope is defined within a function, so it’s only accessible there.
In the example below, you could not access the isFreeShipping variable outside of the function since it is defined within it. However, you can reuse the shippingCost variable and the addShippingCost function in other functions.
var shippingCost = 10; // Global scope function addShippingCost(price) { var isFreeShipping = freeShipping(price) // Function-Local scope if (isFreeShipping) { return price; } else { return price + shippingCost; }};
When declaring variables in your code, consider scope carefully. If you need to access a variable in multiple functions, declare it globally. For any variables you only need within a specific function, set them within that function for better organization.

Topic 3: String Methods
Now that you have been introduced to the string data type, let’s discuss how many actions you can execute on strings.
Using string methods, you can manipulate or extract specific parts of the text using string methods. While there are many different string methods that you should learn about, let’s focus on the .split() method.
Imagine you have shoe sizes stored in a string using various sizing systems, and you want to extract each size into a variable.
Since a forward slash separates the sizes, we add that into the brackets of the method to denote where we need to split the string. The result is an array with each of the split elements.
Indexing lets you define a new variable for the US shoe size (and the other sizing systems).
var usShoeSize = shoeSize.split('/')[0];
While the .split() method is handy, it is just the tip of the iceberg! Some additional string methods you may find helpful include:
- .slice() – Extracts the indicated part of a string and returns a new string.
- .concat() – Returns two or more joined strings.
- .lowerCase() – Returns the specified string in all lowercase.
- .upperCase() – Returns the specified string in all upper case.
- And more!
There is plenty more in the world of string methods, so you are encouraged to explore the JavaScript string further and how to manipulate it in exciting ways.
Topic 4: Array Methods & Loops
Array Methods
As we have already touched on, arrays are like lists of organized information, making storing and arranging information from various data types easy. As with strings, you can also manipulate and transform arrays with their own methods.
Some practical array methods include:
- .push() – Adds one or more elements to the end of an array and returns the new length of the array (Google Tag Manager’s dataLayer is using it)
- .pop() – Removes and returns the last element in the array.
- .find() – Finds and returns the first element in an array that meets the specified condition without changing the original array.
- .slice() – Not to be confused with .splice(), this method returns the part of the array between two specified indices as a new array.
- .map() – Returns a new array after calling a function on each element of the original array
- .forEach() – Allows you to go through each element in an array and perform an action using that element, but – unlike .map() – it doesn’t return anything (like a loop, which we cover next).
- .includes() – Returns a boolean based on whether an array contains the specified element (this method is case sensitive).
- .filter() – Returns a new array containing each element in the original array that met the specified condition.
- .reduce() – Returns a single element by applying the specified “reducer” function on each element on the array (left-to-right).
It will take some time to get comfortable with all the different array methods, but there are plenty of resources to help you out.
Loops
Now, imagine that you have a basket of fruit, and each piece of fruit represents an item in an array. Now, think of a loop as your hand repeatedly grabbing a piece of fruit. With each grab, you can inspect, modify, or perform some action on the fruit.
One at a time, loops permit you to interact with the elements of an array. This allows for an efficient way to perform repeated actions or make decisions based on the contents of an array (or fruit basket).
Consider a scenario where you have an array of objects containing product descriptions. Each object has a “price” key represented as a string with a dollar sign ($). Sending this data to a third-party analytics tool may pose problems, as these tools typically prefer price without currency symbols.
How could array methods and loops help us here? The solution is straightforward – you can utilize loops with the .replace() method to iterate through each object and remove the currency symbol.
Loops and array methods elevate your ability to extract valuable insights from your site. Continue exploring the depths of array methods and loops, and you may find yourself feeling the need to buy a hoodie soon…
Topic 5: DOM – Document Object Model
The Document Object Model – mainly called the DOM – is a dynamic representation of the structure and content of a website. You can imagine it as a tree-like structure, with various branches showing how site elements are embedded within each other.
When you open a website, your browser downloads an HTML file from the website’s server and generates what you see on the site using HTML, CSS, and JavaScript. Then, the DOM is built, allowing access to specific values from the website with the help of JavaScript.
You may recognize the DOM from Google Tag Manager and Google Analytics 4. While developers are not directly manipulating the DOM to implement GA4, your site’s embedded GTM tracking code contains JavaScript functions that interact with the DOM to collect data.
If you’ve used Tag Assistant, this may look familiar:
When users visit your site, the Google Analytics 4 tracking code uses DOM events – which “listen” for user actions – to track when events occur, like pageviews and element clicks. You can add additional listeners to look for specific interactions on your site, collect data on those interactions and send them to GA4.
Google Tag Manager also has existing features to use the DOM Element variable to gather values from it. You can read more about it here.
JavaScript for Google Tag Manager: Final Words
You made it to the end! That wasn’t so bad, right? Starting with these five topics is a significant first step to boosting your analytics and GTM setups. Just like learning any language, it takes practice and repetition.
For beginners exploring Google Tag Manager, it may seem surprising that learning JavaScript is encouraged, given the user-friendly interface of the tool and Google’s promise to “avoid developers”.
However, diving into JavaScript will give you the confidence you need to collect more detailed information using custom HTML tags and JavaScript variables. While implementing tags and variables directly in the dataLayer (and cooperating with developers) is still the best practice, this is a great alternative when IT resources are unavailable.
As you get more comfortable with JavaScript, you can explore the ever-growing list of JavaScript snippets for GTM that you may find helpful. There could be things that JavaScript can help you uncover that you never knew were possible, like checking if a visitor uses an ad-blocker or adding a copyright notice to text copied from your site.
The internet is your oyster, so go out and seize the day-ta! (pun intended).

2 COMMENTS
Thank you so much for this article!
I am in a good to great level in GTM (thanks to you and other giants)
I was wondering where can I learn about the "developer tools" in that regards, to test and see things in the console, or Application concerning Cookies/Storage and thing of that sort.
I explain that in my intermediate/advanced GTM courses