This is one of the #GTMTips posts I was sure I already wrote. So it was a slight surprise when I realized that I had never really touched this aspect of Google Tag Manager.
It’s short and sweet advice again. Today we will learn How to check if a variable is undefined using Google Tag Manager.
Simmer . Newsletter
Subscribe to the Simmer newsletter to get the latest news and content from Simo Ahava right in your inbox!
Tip 73: Check for undefined variable values
If the variable
undefined It is done like this:
function checkIfUndefined(variable) return typeof variable === 'undefined';
true If the variable whose state you want to check is already
However, there is an easier way. Google Tag Manager does some magic and lets you search for it
undefined Type using a simple string check. This might sound a little funky, and it is, but it’s currently the fastest way to check it out
The method itself is really simple. In the trigger where you want to run the scan, just create a new condition that checks if the given variable is or not is not equal
undefined, Such that:
This operator is triggered if the value in Page Type is not
Note that this only checks for
undefined variables. It does not work with others falsify values like
NaN. For these, you’ll have to do additional checks, and you can even use a regular expression:
Worker Does not match regular expression (ignore case) ^ (unknown | null | 0 | error | NaN |) $
Some issues with the GTM approach can arise if you already have a string literal, for example
"undefined" as a variable value. It’s not an impossible scenario to conjure up, because “unspecified” is a word that has functional depth in the English language. There is no way for GTM to distinguish between this valid string value and
function() var variableToValidate = Some Variable; return !!variableToCheckForFalsy;
true If the variable contains a true and non-false value (eg sincerity) value and
false Unlike that.
By the way, I didn’t make up this stuff sincerity And falsify Terms. Terminology is accepted in programming.