Custom JavaScript Variables in Google Tag Manager

What they are, how they work how you can use them to your advantage



owntag Founder

published June 8, 2021

To start off, we have to make an important distinction: This article is about Custom JavaScript Variables. There are the very similarly named JavaScript Variables in Google Tag Manager and while they are interesting, too, they will be the topic of a different article. Until then, you can read up on those in my article about JavaScript Variables.

What are they?

Custom JavaScript Variables are the most versatile of all Google Tag Manager variable types. While the other types are more purpose-built templates, you have complete freedom with your own code here.

Like all GTM variables, they will return a value which you can then use in tags or other variables. With your JavaScript code, you can create the logic that defines how that value is calculated.

The type of the returned value is also up to you, it can be any JavaScript type like a String, a Number, an Array or even an HTML Element.

How do they work?

Every Custom Javascript Variable consists of a function which is defined like this:

function() {

Under the hood, Google Tag Manager will execute that function and use its return value. Wherever you reference the Custom JavaScript Variable like {{myFavoriteVariable}}, GTM will insert the return value of the function.

If you typed the above example into GTM, you’d get the error message

The javaScript must define a function with a return value.

because GTM saw that we didn’t use a return statement in the code.

function() {
    return "Hello, World"

This is now a valid function that returns a string.

Use in a Custom HTML tag

Imagine you’ve saved it with the name “js.helloWorld”. You could then reference it in a Custom HTML Tag like this:


Use in a tag template

You can also use your Custom JavaScript variables in tag templates, for example a GA4 tag. Here’s how you could 50/50 split your traffic to two different GA4 Data Streams:

// Randomly returns one of two Measurement IDs
function () {
  if (Math.random() < 0.5) {
    return "G-12345667890"
  else return "G-0987654321"
A Custom JavaScript variable in the GTM UI

You can then reference the variable in your tag template:

A GA4 tag in the GTM UI that references the js.randomMeasurementId

Useful collections of Custom JS variables by Ana Kravitz

  • Value of the Closest Parent ID
  • Text of the Closest Specific Parent Class
  • Up and Down the DOM
  • Hit Timestamp
  • Visitor IP Address
  • GA Client ID
  • List of SKUs
  • Full URL

Digital Marketing Blog by Aleksandrs Pasters

  • Lowercase value
  • Parse a string and return a specific element
  • Get form field value
  • Get parent element inner text
  • Check if value is not empty
  • Return the clicked element index (position)
  • Search for a specific text on the page

Macro Magic For Google Tag Manager by Simo Ahava

  • Client time
  • Random number for sampling
  • Return file extension of clicked link
  • Return file name of clicked link
  • Check if clicked link is internal
  • Get clientID using _ga cookie
  • Get clientID using ga.getAll()
  • hitCallback with a Universal Analytics tag
  • Return URL path + query string
  • Property ID lookup with hostname
  • Track debug hits to different property ID
  • Get title attribute of document
  • Check if browser has cookies enabled
  • A bunch of useful Auto-Event Variable extensions
  • Detect mobile browser

Closures: Functions returning functions

One of the most useful things about JavaScript functions is that they can take parameters as input. That means they can alter their output based on what you put in. While Custom JavaScript Variables are functions, they can’t take parameters. Imagine for example a simple function that doubles any number you give it. Sadly, this will not work:

// js.double
function(x) {
    // Return after doubling the input
    return x * 2

You can, however, return a function that returns another function. And that returned function can then take parameter. These types of functions that return other functions are sometimes called closures.

function() {
    var double = function(x){
        return x * 2
    return double

Inside the outer function that is required for every Custom JavaScript Variable, we define another function and assign it to the variable name double. Then, we return that named function. In a Custom HTML Tag, we could then use and re-use the function like this:

    // This would work, but would need three individual variable
    // resolutions which is not optimal for performance

    // Better: Scope locally so the GTM variable only has to be
    // resolved once
    var doubleNumber = {{js.double}};
    // Expected output:
    // 4
    // 8
    // 12

Example for reusable functions / closures in GTM

The syntax used to set a cookie with JavaScript’s document.cookie API is not very intuitive, you need quite a lot of code for that. Instead of duplicating that complex code across all the Custom HTML Tags where you’d like to set a cookie, it makes much more sense to reuse the same code across multiple tags.

Here’s what you need:

The Custom JavaScript Variable

function() {
	var setCookie = function (cookieName, cookieValue, expirationInMinutes, domain) {
		var expirationTime = expirationInMinutes * 60 * 1000;
		var date = new Date();
		var dateTimeNow = date.getTime();

		date.setTime(dateTimeNow + expirationTime);
		var expirationTime = date.toUTCString();
		document.cookie = cookieName+"="+cookieValue+"; expires="+expirationTime+"; path=/; domain="+domain;
	return setCookie

And then you can set your cookies inside your Custom HTML tags like this:

    var setCookie = {{js.setCookie}};
    setCookie("myCookie", "myCookieValue", 60, "")
    setCookie("myCookie2", "myCookieValue", 60, "")
    setCookie("myCookie3", "myCookieValue", 60, "")

Become a Server Side Tagging Pro with owntag

Take control of your digital data collection with Server Side Tagging and Server Side GTM – easily hosted with owntag.

App screenshot