Now this function, while useful, isn’t exactly re-usable. Since we are not able to pass any arguments to the function, this can only convert “the text within an element that was clicked” to lowercase. If you’re wanting to convert a different variable, like a URL query parameter, you would need to create a duplicate variable and function using the variable for that query parameter. Of course, if you are only creating a couple of duplicate functions for your entire implementation, then this is not a big deal, but if you find yourself constantly creating them, then problems can arise. (It also goes against a key software development principle, DRY or Don’t Repeat Yourself.) The good news is that there is a simple solution, utility variables.
What is a utility variable?
We are still defining a single anonymous function that returns a value, but our value is another function that accepts three arguments, name, value, and daysTilExp. When calling this Variable, we will pass in these parameters and receive a cookie definition to set the cookie. To call this function, you simply invoke it the same way you would any other JS function, using the Variable Name as the function’s name:
The above call will set a cookie, turnips, with the value, ripe, and an expiration in 7 days. To set a separate cookie, you would just call the same function passing in the new parameters. This single function is infinitely reusable for your cookie setting needs across your entire implementation. Now doesn’t that sound better than creating countless duplicates to achieve the same thing?
Google Analytics Get Function Example
Let’s take a look at another example, this time to get a GA tracker object by its Web Property ID:
Like our cookie builder example, this function simply returns a function that requires a parameter, this time a Web Property ID. This function will then search for the tracker with that ID and return it if found, otherwise, it returns undefined. This function can also be chained with, or used within, another utility variable to retrieve a specific field from the tracker, like the Client ID:
These are just a couple of examples but the use cases for Utility Variables are nearly endless, and they will help you cut down on the bloat that can come with large tracking implementations.
Do you plan on using any of these for your tracking needs? If so, let us know in the comments. If you would like some assistance with managing a complex tracking implementation in Google Tag Manager, let our Data Intelligence Team know.