{"id":163714,"date":"2025-03-29T21:01:23","date_gmt":"2025-03-29T21:01:23","guid":{"rendered":"https:\/\/som2nypost.com\/analytics\/javascript-101-for-gtm-part-2\/"},"modified":"2025-03-29T21:01:23","modified_gmt":"2025-03-29T21:01:23","slug":"javascript-101-for-gtm-part-2","status":"publish","type":"post","link":"https:\/\/som2nypost.com\/?p=163714","title":{"rendered":"JavaScript 101 For GTM: Part 2"},"content":{"rendered":"<p> <br \/>\n<\/p>\n<div>\n<p>It\u2019s been an awesome summer, with temperatures soaring in the global warming range throughout our northern country. The heat has given me ample reason to not be near a computer, but now it\u2019s time to mine some JavaScript wisdom again. Here\u2019s the second part of my JavaScript for <a href=\"https:\/\/www.google.com\/tagmanager\">Google Tag Manager<\/a> series. The <a href=\"https:\/\/www.simoahava.com\/analytics\/javascript-101-gtm-part-1\/\">first part<\/a> focused on GTM specific tips and tricks, and I hope that while reading it, you were treated to another grand example of the flexibility of this wonderful tool.<\/p>\n<p>This second part was supposed to be more about general JavaScript practices, but I saw myself going back to the DOM with every step. So the theme here is the elusive Document Object Model. It\u2019s a defining quality of JavaScript in web development, and understanding its mechanics is key to understanding how tag management solutions work as well.<\/p>\n<p>Here\u2019s the list of topics:<\/p>\n<ol>\n<li>\n<p>The Document Object Model (DOM)<\/p>\n<\/li>\n<li>\n<p>The DOM API<\/p>\n<\/li>\n<li>\n<p>JavaScript injection + GTM<\/p>\n<\/li>\n<li>\n<p>Handling false<\/p>\n<\/li>\n<\/ol>\n<p>Here we go again. I implore you to take a look at the <a href=\"https:\/\/www.simoahava.com\/analytics\/javascript-101-gtm-part-1\/\">list of resources<\/a> I linked to in the previous post. They should serve you really well in your journey towards JavaScript enlightenment.<\/p>\n<p>                <span class=\"simmer\"><br \/>\n  <span class=\"close\">X<\/span><\/p>\n<p>\n    <span class=\"fa fa-md fa-bell\"\/><br \/>\n    <strong>The Simmer Newsletter<\/strong>\n  <\/p>\n<p>\n    Subscribe to the <a href=\"https:\/\/www.simoahava.com\/newsletter\/\">Simmer newsletter<\/a> to get the latest news and content from Simo Ahava into your email inbox!\n  <\/p>\n<p>  <\/span><\/p>\n<h2 id=\"1-the-document-object-model-dom\">1. The Document Object Model (DOM)<\/h2>\n<p>Here\u2019s a very, very simplified account of how a browser works:<\/p>\n<ol>\n<li>\n<p>The browser sends a request to the web server to retrieve a web document<\/p>\n<\/li>\n<li>\n<p>This document is just an annotated source code file, so it needs to be parsed into a format the browser can interpret<\/p>\n<\/li>\n<li>\n<p>The document is parsed into a parsed node tree, whose syntax is very standardized<\/p>\n<\/li>\n<li>\n<p>The node tree is then rendered as a web page, which can be viewed in the browser window<\/p>\n<\/li>\n<li>\n<p>The node tree is actually the Document Object Model (DOM), which also provides an interface for interacting with elements in the tree<\/p>\n<\/li>\n<\/ol>\n<p>In short, what you see when looking at the <strong>page source<\/strong> of a web page in your browser is just that: the source code of the page. It isn\u2019t the <em>final<\/em> product, since the source code is parsed into a format which can be better understood by browsers.<\/p>\n<div style=\"aspect-ratio: 1327 \/ 642;\" class=\"figure nocaption\">\n<p>    <a href=\"https:\/\/www.simoahava.com\/images\/2014\/07\/browser-function.jpg\" title=\"How a browser works\"><\/p>\n<p>    <img decoding=\"async\" class=\"fig-img\" height=\"642\" width=\"1327\" loading=\"lazy\" src=\"https:\/\/www.simoahava.com\/images\/2014\/07\/browser-function.jpg#ZgotmplZ\" alt=\"How a browser works\"\/><\/p>\n<p>    <\/a><\/p>\n<\/div>\n<p>If you\u2019ve messed around with a tag management system or with JavaScript, chances are you already know all this. The DOM is both a representation of on-page elements and an <em>interface<\/em> (more on this in the next chapter) which describes a standard for interacting with these elements. It\u2019s called the Document <strong>Object<\/strong> Model because the HTML elements you lovingly create in your source code are represented as objects, or nodes, or branches of a tree, in a top-level object called <strong>document<\/strong>. So when you <em>tag<\/em> a section of text as a DIV element in HTML, you are actually creating a new node with tag name DIV into the document hierarchy as a new element that can be interacted with.<\/p>\n<p>So the DOM and your HTML document are related, in that they share the same elements, but they are not the same thing. The DOM is the browser\u2019s interpretation of the HTML document. The fact that it\u2019s standardized makes sure that all your sloppiness in HTML markup is glossed over in a perfectly structured DOM.<\/p>\n<p>If you want to take a look at what the document object looks like for any given page, just open a JavaScript console, type <code>document<\/code> and press enter.<\/p>\n<div style=\"aspect-ratio: 645 \/ 188;\" class=\"figure nocaption\">\n<p>    <a href=\"https:\/\/www.simoahava.com\/images\/2014\/07\/document-object.jpg\" title=\"Document Object in JavaScript Console\"><\/p>\n<p>    <img decoding=\"async\" class=\"fig-img\" height=\"188\" width=\"645\" loading=\"lazy\" src=\"https:\/\/www.simoahava.com\/images\/2014\/07\/document-object.jpg#ZgotmplZ\" alt=\"Document Object in JavaScript Console\"\/><\/p>\n<p>    <\/a><\/p>\n<\/div>\n<p>Almost all JavaScript that interacts with a page (such as analytics tags) utilizes the DOM. This is because representing a document with a collection of objects allows for scripting languages such as JavaScript to mimic the syntax of more traditional, object-oriented programming languages. Also, using a standardized set of objects and functions in the DOM normalizes the potentially chaotic and horrible markup that many, many web pages out there display.<\/p>\n<p>The thing about the DOM is that if you understand its basic functions and if you read up on the standard, you should be inspired to create better markup as well. If the ID attribute was just a CSS selector to you before, after realizing what a crucial part it plays in the unique identification of a single DOM node, you\u2019ll be more inclined (hopefully) to utilize it in the future in all relevant markup situations.<\/p>\n<p>The DOM is a huge standard and there\u2019s lots to learn. The best way to learn is to inspect objects in the model by utilizing the JavaScript console. Reading up on GTM articles is a good way to brush up your skills as well, since almost all GTM customizations have to do with manipulating the DOM in some way.<\/p>\n<p>There\u2019s also the Browser Object Model (BOM), which is a de facto standard for interacting with the browser window. The BOM houses the <strong>window<\/strong> object, which, in turn, contains all the global variables and functions of the page AND the document object. So when you type <code>document<\/code> in the JavaScript console, you are actually accessing the <code>window.document<\/code> object.<\/p>\n<p>Confusing? Perhaps, but in the end it\u2019s all quite logical. The DOM is a necessary interface between the client and the HTML document, because so much of today\u2019s web development revolves around dynamic and often subtle modification of the web pages. That\u2019s how you get your animations, transitions, event handlers and so forth to work.<\/p>\n<p><strong>FURTHER READING:<\/strong><\/p>\n<h2 id=\"2-the-dom-api\">2. The DOM API<\/h2>\n<p>The DOM API is actually the DOM itself (remember, it\u2019s a standard for interacting with the document), but for clarity\u2019s sake I use the term API here (<strong>a<\/strong>pplication <strong>p<\/strong>rogramming <strong>i<\/strong>nterface). Interacting with the document is done via the methods and objects exposed by the API.<\/p>\n<p>When using JavaScript (as most often is the case) to interact with the DOM, all calls should naturally be in the context of a <code><script\/><\/code> element. This means that you either fetch the JavaScript in the declaration itself, or you add the code inline. Certain attributes such as \u201conclick\u201d allow you to add JavaScript directly to the context of a HTML element without using <code><script\/><\/code>, but the most common instance is having the <code><script\/><\/code> tag in place.<\/p>\n<p>There are many functions and objects you can access via the DOM, so I won\u2019t go into too much detail here. However, I will add an example of what DOM manipulation means in terms of HTML vs. JavaScript. Here\u2019s a typical HTML passage in a normal web page:<\/p>\n<div class=\"highlight\">\n<pre style=\"background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4\"><code class=\"language-html\" data-lang=\"html\">div <span style=\"color:#1e90ff\">id<\/span>=<span style=\"color:#a50\">\"content\"<\/span>&gt;\n  span <span style=\"color:#1e90ff\">class<\/span>=<span style=\"color:#a50\">\"header\"<\/span>&gt;Why Four Strings Is Enough<span style=\"color:#1e90ff;font-weight:bold\">span<\/span>&gt;\n  p <span style=\"color:#1e90ff\">class<\/span>=<span style=\"color:#a50\">\"paragraph\"<\/span>&gt;Many dismiss the ukulele because it only has four strings. However, it has more strings than a typical balalaika.<span style=\"color:#1e90ff;font-weight:bold\">p<\/span>&gt;\n  div <span style=\"color:#1e90ff\">id<\/span>=<span style=\"color:#a50\">\"request-access\"<\/span>&gt;\n    p <span style=\"color:#1e90ff\">class<\/span>=<span style=\"color:#a50\">\"paragraph\"<\/span>&gt;Request access to ukulele vault by sending mail to span <span style=\"color:#1e90ff\">class<\/span>=<span style=\"color:#a50\">\"email\"<\/span>&gt;<a href=\"https:\/\/www.simoahava.com\/cdn-cgi\/l\/email-protection\" class=\"__cf_email__\" data-cfemail=\"43362836032f262f266d202c2e\">[email\u00a0protected]<\/a><span style=\"color:#1e90ff;font-weight:bold\">span<\/span>&gt;<span style=\"color:#1e90ff;font-weight:bold\">p<\/span>&gt;\n  <span style=\"color:#1e90ff;font-weight:bold\">div<\/span>&gt;\n<span style=\"color:#1e90ff;font-weight:bold\">div<\/span>&gt;<\/code><\/pre>\n<\/div>\n<p>So there are some unique elements where I utilize the ID attribute, and some elements which are reused, represented by the CLASS attribute. It\u2019s important to remember that if you use ID, you should only ever have one such element on the page. Otherwise you will make life difficult for anyone wishing to manipulate the element using the DOM API (plus it won\u2019t be valid HTML).<\/p>\n<p>Here are some examples of JavaScript functions I can use to interact with the document:<\/p>\n<div class=\"highlight\">\n<pre style=\"background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4\"><code class=\"language-javascript\" data-lang=\"javascript\"><span style=\"color:#00a\">var<\/span> content = <span style=\"color:#0aa\">document<\/span>.getElementById(<span style=\"color:#a50\">\"content\"<\/span>);\n<\/code><\/pre>\n<\/div>\n<p>This stores the whole #content node with all its children into the JavaScript variable <code>content<\/code>. I can then use other functions of the DOM to manipulate the node further.<\/p>\n<div class=\"highlight\">\n<pre style=\"background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4\"><code class=\"language-javascript\" data-lang=\"javascript\">content.setAttribute(<span style=\"color:#a50\">\"id\"<\/span>, <span style=\"color:#a50\">\"main-content\"<\/span>);\n<\/code><\/pre>\n<\/div>\n<p>Changes the ID attribute of the #content DIV to #main-content. Here I utilize the JavaScript object where I stored the entire #content node just before.<\/p>\n<div class=\"highlight\">\n<pre style=\"background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4\"><code class=\"language-javascript\" data-lang=\"javascript\"><span style=\"color:#00a\">var<\/span> classArray = <span style=\"color:#0aa\">document<\/span>.getElementsByClassName(<span style=\"color:#a50\">\"paragraph\"<\/span>);\n<\/code><\/pre>\n<\/div>\n<p>Stores all elements with CLASS .paragraph in an Array object referred to as <code>classArray<\/code>.<\/p>\n<div class=\"highlight\">\n<pre style=\"background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4\"><code class=\"language-javascript\" data-lang=\"javascript\">console.log(classArray[<span style=\"color:#099\">0<\/span>].innerHTML);\n<\/code><\/pre>\n<\/div>\n<p>Writes the entire HTML content of the first P element with class .paragraph into the console.<\/p>\n<div class=\"highlight\">\n<pre style=\"background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4\"><code class=\"language-javascript\" data-lang=\"javascript\">alert(<span style=\"color:#0aa\">document<\/span>.getElementById(<span style=\"color:#a50\">\"request-access\"<\/span>).children.length);\n<\/code><\/pre>\n<\/div>\n<p>Pops up a dialog box with the number of child nodes for the HTML element with ID #request-access. In this case, the alert will contain the number 1.<\/p>\n<p>There are many, many ways to interact with the document, its objects and functions using the interface of the DOM. You should be pretty comfortable with these especially if you want to do some advanced tag management and web analytics tweaking.<\/p>\n<p><strong>FURTHER READING:<\/strong><\/p>\n<h2 id=\"3-javascript-injection--gtm\">3. JavaScript injection + GTM<\/h2>\n<p>Now that you understand perfectly how the DOM works, you\u2019re ready for the next big thing: code injection.<\/p>\n<p>The whole premise of a JavaScript tag management system revolves around code injection. That\u2019s why you\u2019re fine with just adding <a href=\"https:\/\/www.simoahava.com\/analytics\/container-snippet-gtm-secrets-revealed\/\">the container snippet<\/a> into your source code when installing GTM. By adding this seemingly harmless piece of code into your source code, you\u2019re actually giving permission to the <strong>gtm.js<\/strong> library to inject more and more code, elements, and functions into your DOM.<\/p>\n<p>And what is this injected code? Your tags and macros, of course!<\/p>\n<p>Let\u2019s see how injection works with a simple example of adding a new <code><script\/><\/code> node into the HEAD of the document:<\/p>\n<div class=\"highlight\">\n<pre style=\"background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4\"><code class=\"language-javascript\" data-lang=\"javascript\"><span style=\"color:#00a\">var<\/span> s = <span style=\"color:#0aa\">document<\/span>.createElement(<span style=\"color:#a50\">\"script\"<\/span>);\ns.innerHTML = <span style=\"color:#a50\">\"alert('Injection successful');\"<\/span>;\n<span style=\"color:#0aa\">document<\/span>.head.appendChild(s);\n<\/code><\/pre>\n<\/div>\n<ol>\n<li>\n<p>Line 1: A new SCRIPT element is created, but it isn\u2019t attached anywhere yet<\/p>\n<\/li>\n<li>\n<p>Line 2: Some code is added into the content of the new tag<\/p>\n<\/li>\n<li>\n<p>Line 3: The new element is added as the last child of the document HEAD<\/p>\n<\/li>\n<\/ol>\n<p>If you copy-paste this code into a JavaScript console, you should see the pop-up dialog with \u201cInjection successful\u201d.<\/p>\n<p>In this code you utilize the DOM with <code>createElement()<\/code> and <code>appendChild()<\/code> functions, the <code>innerHTML<\/code> property, and the <code>document<\/code> and <code>document.head<\/code> elements in the tree. If you now look at your elements (not the source code) by opening the developer tools of your favorite browser, you should see this new element as the last child of the HEAD.<\/p>\n<div style=\"aspect-ratio: 495 \/ 150;\" class=\"figure nocaption\">\n<p>    <a href=\"https:\/\/www.simoahava.com\/images\/2014\/07\/injection-example.jpg\" title=\"Example of code injection\"><\/p>\n<p>    <img decoding=\"async\" class=\"fig-img\" height=\"150\" width=\"495\" loading=\"lazy\" src=\"https:\/\/www.simoahava.com\/images\/2014\/07\/injection-example.jpg#ZgotmplZ\" alt=\"Example of code injection\"\/><\/p>\n<p>    <\/a><\/p>\n<\/div>\n<p>All the Custom HTML tags you create via GTM are added to you page in a similar fashion. When you visit a page where such a tag is set to fire, the script is injected the moment the firing rule triggers. Any code in the tag is run there and then.<\/p>\n<p>This also highlights the dangers of using a tag management solution to fix \/ hack errors in your web page. Code injection is brutal in the sense that any code within is run verbatim. There are no default checks in place to prevent your code from messing with global objects or your carefully crafted content. Since the DOM API opens <strong>all<\/strong> elements in the tree for manipulation, it\u2019s very easy to create AND destroy something beautiful.<\/p>\n<p>So be careful.<\/p>\n<p><strong>FURTHER READING:<\/strong><\/p>\n<h2 id=\"4-handling-false\">4. Handling false<\/h2>\n<p>This was all too easy so far, so I\u2019ll leave you with something truly mind-boggling.<\/p>\n<p>I\u2019ve written about this phenomenon <a href=\"https:\/\/www.simoahava.com\/analytics\/fun-with-google-tag-manager-part-1\/\">before<\/a>, and I still think its key to understanding how GTM and JavaScript work together.<\/p>\n<p>First of all, I apologize in advance. JavaScript\u2019s treatment of \u201cfalsy\u201d values such as undefined, null, and false is notoriously difficult to understand. Not only is it difficult to understand, it\u2019s even more difficult to teach in an understandable manner.<\/p>\n<p>When talking about \u201ctruthy\u201d and \u201cfalsy\u201d values, we\u2019re not talking strictly about values which are either <em>true<\/em> or <em>false<\/em>. Rather, we mean values which are coerced to either <em>true<\/em> or <em>false<\/em> in a Boolean context. Boolean is a type which holds either <em>true<\/em> or <em>false<\/em> as its value, and a context is Boolean if some statement hinges on whether the expression evaluates to either <em>true<\/em> or <em>false<\/em>.<\/p>\n<p>An if-clause is probably the most used Boolean context. The following piece of code is a prototypical example of type coercion:<\/p>\n<div class=\"highlight\">\n<pre style=\"background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4\"><code class=\"language-javascript\" data-lang=\"javascript\"><span style=\"color:#00a\">if<\/span>(t) {\n  ...<span style=\"color:#00a\">do<\/span> something <span style=\"color:#00a\">if<\/span> t evaluates to <span style=\"color:#00a\">true<\/span>...\n} <span style=\"color:#00a\">else<\/span> <span style=\"color:#00a\">if<\/span> (!t) {\n  ...<span style=\"color:#00a\">do<\/span> something <span style=\"color:#00a\">if<\/span> t evaluates to <span style=\"color:#00a\">false<\/span>...\n}\n<\/code><\/pre>\n<\/div>\n<p>The if-clause is run if <code>t<\/code> is <em>true<\/em>, but it doesn\u2019t mean the <em>value<\/em> of <code>t<\/code> needs to be <em>true<\/em>. Rather, the value of <code>t<\/code> needs to be \u201ctruthy\u201d. The else-clause is run if the value is not \u201ctruthy\u201d but \u201cfalsy\u201d (oh my those are stupid terms).<\/p>\n<p>So in this context, <code>t<\/code> is coerced to Boolean values. It\u2019s easier to go through the values which evaluate to <em>false<\/em>, since there are only six of them.<\/p>\n<p><strong>undefined<br \/>null<br \/>false<br \/>0<br \/>&#8220;\u201d<br \/>NaN<\/strong><\/p>\n<p>So if a variable holds any of these values, it would evaluate to <em>false<\/em> in a Boolean context.<\/p>\n<p>Still with me? Good. For GTM, we are particularly interested in the values <strong>undefined<\/strong> and <strong>null<\/strong>.<\/p>\n<p><strong>undefined<\/strong> is a value (and a type, actually) reserved for variables which have either been declared but have no type assigned to them (via value assignment), OR have not been declared at all. This is very relevant for JavaScript, since often and especially with dynamic web pages many variables receive a value and type only after a specific user interaction (such as a click). If a function is executed before such an interaction and without the check for undefined, the function execution will fail in an ugly JS error.<\/p>\n<p>The two simplest ways to safeguard your variable execution are:<\/p>\n<div class=\"highlight\">\n<pre style=\"background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4\"><code class=\"language-javascript\" data-lang=\"javascript\"><span style=\"color:#00a\">if<\/span>(!t) {\n  alert(<span style=\"color:#a50\">\"t is falsy and perhaps undefined!\"<\/span>);\n}\n<span style=\"color:#00a\">if<\/span>(<span style=\"color:#00a\">typeof<\/span>(t) === <span style=\"color:#00a\">undefined<\/span>) {\n  alert(<span style=\"color:#a50\">\"t is undefined or has not been declared!\"<\/span>);\n}\n<\/code><\/pre>\n<\/div>\n<p>The difference is that using the <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Guide\/Expressions_and_Operators#Logical_operators\">logical not operator<\/a> (!) is recommended when you know the variable has been declared but are not certain if it has a value assigned yet, whereas the <strong>typeof()<\/strong> operator should be used when you are not certain if the variable has been declared at all.<\/p>\n<p>The logical not operator is literally \u201cnot\u201d, so <code>if(!t) { ... }<\/code> is read as <strong>if (t is false is true) { \u2026run this code\u2026 }<\/strong>. Thus, the if-clause is only run if <code>t<\/code> is one of the \u201cfalsy\u201d values listed in the beginning of this chapter.<\/p>\n<p>I can see your head spinning &#8211; again, I apologize!<\/p>\n<p>The thing is, you shouldn\u2019t really use <code>typeof(var)===undefined<\/code>, since you should always be able to see whether a variable has been declared either by looking at the immediate local function context or by looking for the variable in the global object.<\/p>\n<p>Yes, let me explain this as well.<\/p>\n<p>JavaScript has static scope. This means that variables are either always global or scoped to the function they are wrapped in. If a variable is scoped to a function and if you\u2019ve observed best practices in your programming, you should quickly see whether or not a variable has been declared by the time your code is run.<\/p>\n<div class=\"highlight\">\n<pre style=\"background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4\"><code class=\"language-javascript\" data-lang=\"javascript\"><span style=\"color:#00a\">var<\/span> globalVar; <span style=\"color:#aaa;font-style:italic\">\/\/ global variable\n<\/span><span style=\"color:#aaa;font-style:italic\"\/><span style=\"color:#00a\">function<\/span> t() {\n  <span style=\"color:#00a\">var<\/span> localVar; <span style=\"color:#aaa;font-style:italic\">\/\/ local variable\n<\/span><span style=\"color:#aaa;font-style:italic\"\/>  secondVar; <span style=\"color:#aaa;font-style:italic\">\/\/ global but bad code\n<\/span><span style=\"color:#aaa;font-style:italic\"\/>}\nalert(localVar); <span style=\"color:#aaa;font-style:italic\">\/\/ error since trying to access local variable outside function\n<\/span><\/code><\/pre>\n<\/div>\n<p>Another thing to note is that if a variable is scoped globally, it will be a property of the global <code>window<\/code> object. Thus, you can use the logical not operator to check for its absence:<\/p>\n<div class=\"highlight\">\n<pre style=\"background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4\"><code class=\"language-javascript\" data-lang=\"javascript\"><span style=\"color:#00a\">if<\/span>(!<span style=\"color:#0aa\">window<\/span>.t) { something... } <span style=\"color:#aaa;font-style:italic\">\/\/ run something if t is not a global variable\n<\/span><span style=\"color:#aaa;font-style:italic\"\/>...\n<span style=\"color:#00a\">if<\/span>(!t) { something... } <span style=\"color:#aaa;font-style:italic\">\/\/ referenceError if t is not a global variable\n<\/span><\/code><\/pre>\n<\/div>\n<p><strong>When working with GTM and GA<\/strong>, a very important thing to understand is how the DOM API works with elements that are not found on the page. You see, a function such as <code>getElementById()<\/code> or <code>getElementsByTagName()<\/code> will <strong>always<\/strong> return an object. An object, if you remember, was not among the \u201cfalsy\u201d values listed in the beginning. However, this object will have the special value <strong>null<\/strong> if the actual HTML element is not found on the page.<\/p>\n<p>If you stretch your memory again, <strong>null<\/strong> was among the values that are \u201cfalsy\u201d. Thus:<\/p>\n<div class=\"highlight\">\n<pre style=\"background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4\"><code class=\"language-javascript\" data-lang=\"javascript\"><span style=\"color:#00a\">var<\/span> t = <span style=\"color:#0aa\">document<\/span>.getElementById(<span style=\"color:#a50\">\"test\"<\/span>), <span style=\"color:#aaa;font-style:italic\">\/\/ \"test\" exists, will return the DOM element\n<\/span><span style=\"color:#aaa;font-style:italic\"\/>    y = <span style=\"color:#0aa\">document<\/span>.getElementById(<span style=\"color:#a50\">\"testy\"<\/span>); <span style=\"color:#aaa;font-style:italic\">\/\/ \"testy\" does not exist, will return object with value null\n<\/span><span style=\"color:#aaa;font-style:italic\"\/><span style=\"color:#00a\">if<\/span>(<span style=\"color:#00a\">typeof<\/span>(<span style=\"color:#a50\">\"t\"<\/span>) === <span style=\"color:#00a\">undefined<\/span>) { <span style=\"color:#aaa;font-style:italic\">\/\/ does nothing\n<\/span><span style=\"color:#aaa;font-style:italic\"\/>  alert(<span style=\"color:#a50\">\"t is undefined\"<\/span>);\n}\n<span style=\"color:#00a\">if<\/span>(!t) { <span style=\"color:#aaa;font-style:italic\">\/\/ does nothing\n<\/span><span style=\"color:#aaa;font-style:italic\"\/>  alert(<span style=\"color:#a50\">\"t resolves to false\"<\/span>); \n}\n<span style=\"color:#00a\">if<\/span>(t===<span style=\"color:#00a\">null<\/span>) { <span style=\"color:#aaa;font-style:italic\">\/\/ does nothing\n<\/span><span style=\"color:#aaa;font-style:italic\"\/>  alert(<span style=\"color:#a50\">\"t is null\"<\/span>);\n}\n<span style=\"color:#00a\">if<\/span>(<span style=\"color:#00a\">typeof<\/span>(<span style=\"color:#a50\">\"y\"<\/span>) === <span style=\"color:#00a\">undefined<\/span>) { <span style=\"color:#aaa;font-style:italic\">\/\/ does nothing\n<\/span><span style=\"color:#aaa;font-style:italic\"\/>  alert(<span style=\"color:#a50\">\"y is undefined\"<\/span>);\n}\n<span style=\"color:#00a\">if<\/span>(!y) { <span style=\"color:#aaa;font-style:italic\">\/\/ will alert the following message\n<\/span><span style=\"color:#aaa;font-style:italic\"\/>  alert(<span style=\"color:#a50\">\"y resolves to false\"<\/span>);\n}\n<span style=\"color:#00a\">if<\/span>(y===<span style=\"color:#00a\">null<\/span>) { <span style=\"color:#aaa;font-style:italic\">\/\/ will alert the following message\n<\/span><span style=\"color:#aaa;font-style:italic\"\/>  alert(<span style=\"color:#a50\">\"y is null\"<\/span>);\n}\n<\/code><\/pre>\n<\/div>\n<p>So the tips of this chapter are:<\/p>\n<p>**1.**Use the global window object and the logical not operator as a fallback in case a variable hasn\u2019t been declared in global scope.<\/p>\n<p><strong>2.<\/strong> Read through your code to see if a variable has been declared in local (function) scope OR if you\u2019re lazy, use the fallback <code>if(typeof(variable)===undefined) { do something; }<\/code>.<\/p>\n<p><strong>3.<\/strong> Either use the logical not operator with a DOM element, e.g. if(!someDOMElement), OR check for null, e.g. if(someDOMElement===null), to fall back in case a DOM element you are referencing is not found in the DOM.<\/p>\n<p>You don\u2019t want to write a long block of code only to see it miserably explode in JavaScript error mayhem thanks to race conditions or faulty declarations.<\/p>\n<p><strong>FURTHER READING:<\/strong><\/p>\n<h2 id=\"5-conclusions\">5. Conclusions<\/h2>\n<p>I\u2019m a huge, HUGE fan of JavaScript. I love it so much I\u2019m seriously considering naming my first-born with initials that spell JS (Jebediah Simo, for example). I also think that anyone wanting to extend the capabilities of Google Analytics, and DEFINITELY anyone working with Google Tag Manager, should understand at least the basics.<\/p>\n<p>There\u2019s a lot to learn, and the splintered mess of cross-browser issues doesn\u2019t make it any easier. However, lots of ridiculously smart engineers are working on the standard, so if things go smoothly, we should see some pretty cool and facilitating additions in the next release of the language.<\/p>\n<p>Remember, an excellent place for advice on JavaScript, especially related to GA and GTM, is Google+. Be sure to follow the communities, and drop a line if you need any assistance with your code.<\/p>\n<p><a href=\"https:\/\/plus.google.com\/u\/0\/communities\/114481059214254340537\">Google Analytics community in Google+<\/a><\/p>\n<p><a href=\"https:\/\/plus.google.com\/u\/0\/communities\/104865292981489764063\">Google Tag Manager community in Google+<\/a><\/p>\n<\/p><\/div>\n\n","protected":false},"excerpt":{"rendered":"<p>It\u2019s been an awesome summer, with temperatures soaring in the global warming range throughout our northern country. The heat has given me ample reason to not be near a computer, but now it\u2019s time to mine some JavaScript wisdom again. Here\u2019s the second part of my JavaScript for Google Tag Manager series. The first part [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":163715,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[12033],"tags":[32680,29091,3341],"dealstore":[],"offerexpiration":[],"class_list":["post-163714","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-analytics","tag-gtm","tag-javascript","tag-part"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.4 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>JavaScript 101 For GTM: Part 2 - Som2ny Network<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/som2nypost.com\/?p=163714\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"JavaScript 101 For GTM: Part 2 - Som2ny Network\" \/>\n<meta property=\"og:description\" content=\"It\u2019s been an awesome summer, with temperatures soaring in the global warming range throughout our northern country. The heat has given me ample reason to not be near a computer, but now it\u2019s time to mine some JavaScript wisdom again. Here\u2019s the second part of my JavaScript for Google Tag Manager series. The first part [&hellip;]\" \/>\n<meta property=\"og:url\" content=\"https:\/\/som2nypost.com\/?p=163714\" \/>\n<meta property=\"og:site_name\" content=\"Som2ny Network\" \/>\n<meta property=\"article:published_time\" content=\"2025-03-29T21:01:23+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/som2nypost.com\/wp-content\/uploads\/2025\/03\/browser-function.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1\" \/>\n\t<meta property=\"og:image:height\" content=\"1\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"admin\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"admin\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"15 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/som2nypost.com\/?p=163714#article\",\"isPartOf\":{\"@id\":\"https:\/\/som2nypost.com\/?p=163714\"},\"author\":{\"name\":\"admin\",\"@id\":\"https:\/\/som2nypost.com\/#\/schema\/person\/a66cfe5cdcbceba9b5562fe085bcaba4\"},\"headline\":\"JavaScript 101 For GTM: Part 2\",\"datePublished\":\"2025-03-29T21:01:23+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/som2nypost.com\/?p=163714\"},\"wordCount\":2670,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/som2nypost.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/som2nypost.com\/?p=163714#primaryimage\"},\"thumbnailUrl\":\"https:\/\/som2nypost.com\/wp-content\/uploads\/2025\/03\/browser-function.jpg\",\"keywords\":[\"GTM\",\"JavaScript\",\"PART\"],\"articleSection\":[\"Analytics\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/som2nypost.com\/?p=163714#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/som2nypost.com\/?p=163714\",\"url\":\"https:\/\/som2nypost.com\/?p=163714\",\"name\":\"JavaScript 101 For GTM: Part 2 - Som2ny Network\",\"isPartOf\":{\"@id\":\"https:\/\/som2nypost.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/som2nypost.com\/?p=163714#primaryimage\"},\"image\":{\"@id\":\"https:\/\/som2nypost.com\/?p=163714#primaryimage\"},\"thumbnailUrl\":\"https:\/\/som2nypost.com\/wp-content\/uploads\/2025\/03\/browser-function.jpg\",\"datePublished\":\"2025-03-29T21:01:23+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/som2nypost.com\/?p=163714#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/som2nypost.com\/?p=163714\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/som2nypost.com\/?p=163714#primaryimage\",\"url\":\"https:\/\/som2nypost.com\/wp-content\/uploads\/2025\/03\/browser-function.jpg\",\"contentUrl\":\"https:\/\/som2nypost.com\/wp-content\/uploads\/2025\/03\/browser-function.jpg\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/som2nypost.com\/?p=163714#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/som2nypost.com\/?bp_activities=1\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"JavaScript 101 For GTM: Part 2\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/som2nypost.com\/#website\",\"url\":\"https:\/\/som2nypost.com\/\",\"name\":\"Som2ny Network\",\"description\":\"Daily Deals\",\"publisher\":{\"@id\":\"https:\/\/som2nypost.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/som2nypost.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/som2nypost.com\/#organization\",\"name\":\"Som2ny Network\",\"url\":\"https:\/\/som2nypost.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/som2nypost.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/som2nypost.com\/wp-content\/uploads\/2026\/07\/4a0953c4-logo-300x86-1.png\",\"contentUrl\":\"https:\/\/som2nypost.com\/wp-content\/uploads\/2026\/07\/4a0953c4-logo-300x86-1.png\",\"width\":300,\"height\":86,\"caption\":\"Som2ny Network\"},\"image\":{\"@id\":\"https:\/\/som2nypost.com\/#\/schema\/logo\/image\/\"}},{\"@type\":\"Person\",\"@id\":\"https:\/\/som2nypost.com\/#\/schema\/person\/a66cfe5cdcbceba9b5562fe085bcaba4\",\"name\":\"admin\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/som2nypost.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/729ae85bf62b9917e93538db2f2688ca?s=96&r=g&default=https%3A%2F%2Fsom2nypost.com%2Fwp-content%2Fplugins%2Fbuddypress-first-letter-avatar%2Fimages%2Fdefault%2F96%2Flatin_a.png\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/729ae85bf62b9917e93538db2f2688ca?s=96&r=g&default=https%3A%2F%2Fsom2nypost.com%2Fwp-content%2Fplugins%2Fbuddypress-first-letter-avatar%2Fimages%2Fdefault%2F96%2Flatin_a.png\",\"caption\":\"admin\"},\"sameAs\":[\"https:\/\/som2nypost.com\"],\"url\":\"https:\/\/som2nypost.com\/?author=1\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"JavaScript 101 For GTM: Part 2 - Som2ny Network","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/som2nypost.com\/?p=163714","og_locale":"en_US","og_type":"article","og_title":"JavaScript 101 For GTM: Part 2 - Som2ny Network","og_description":"It\u2019s been an awesome summer, with temperatures soaring in the global warming range throughout our northern country. The heat has given me ample reason to not be near a computer, but now it\u2019s time to mine some JavaScript wisdom again. Here\u2019s the second part of my JavaScript for Google Tag Manager series. The first part [&hellip;]","og_url":"https:\/\/som2nypost.com\/?p=163714","og_site_name":"Som2ny Network","article_published_time":"2025-03-29T21:01:23+00:00","og_image":[{"url":"https:\/\/som2nypost.com\/wp-content\/uploads\/2025\/03\/browser-function.jpg","width":1,"height":1,"type":"image\/jpeg"}],"author":"admin","twitter_card":"summary_large_image","twitter_misc":{"Written by":"admin","Est. reading time":"15 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/som2nypost.com\/?p=163714#article","isPartOf":{"@id":"https:\/\/som2nypost.com\/?p=163714"},"author":{"name":"admin","@id":"https:\/\/som2nypost.com\/#\/schema\/person\/a66cfe5cdcbceba9b5562fe085bcaba4"},"headline":"JavaScript 101 For GTM: Part 2","datePublished":"2025-03-29T21:01:23+00:00","mainEntityOfPage":{"@id":"https:\/\/som2nypost.com\/?p=163714"},"wordCount":2670,"commentCount":0,"publisher":{"@id":"https:\/\/som2nypost.com\/#organization"},"image":{"@id":"https:\/\/som2nypost.com\/?p=163714#primaryimage"},"thumbnailUrl":"https:\/\/som2nypost.com\/wp-content\/uploads\/2025\/03\/browser-function.jpg","keywords":["GTM","JavaScript","PART"],"articleSection":["Analytics"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/som2nypost.com\/?p=163714#respond"]}]},{"@type":"WebPage","@id":"https:\/\/som2nypost.com\/?p=163714","url":"https:\/\/som2nypost.com\/?p=163714","name":"JavaScript 101 For GTM: Part 2 - Som2ny Network","isPartOf":{"@id":"https:\/\/som2nypost.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/som2nypost.com\/?p=163714#primaryimage"},"image":{"@id":"https:\/\/som2nypost.com\/?p=163714#primaryimage"},"thumbnailUrl":"https:\/\/som2nypost.com\/wp-content\/uploads\/2025\/03\/browser-function.jpg","datePublished":"2025-03-29T21:01:23+00:00","breadcrumb":{"@id":"https:\/\/som2nypost.com\/?p=163714#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/som2nypost.com\/?p=163714"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/som2nypost.com\/?p=163714#primaryimage","url":"https:\/\/som2nypost.com\/wp-content\/uploads\/2025\/03\/browser-function.jpg","contentUrl":"https:\/\/som2nypost.com\/wp-content\/uploads\/2025\/03\/browser-function.jpg"},{"@type":"BreadcrumbList","@id":"https:\/\/som2nypost.com\/?p=163714#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/som2nypost.com\/?bp_activities=1"},{"@type":"ListItem","position":2,"name":"JavaScript 101 For GTM: Part 2"}]},{"@type":"WebSite","@id":"https:\/\/som2nypost.com\/#website","url":"https:\/\/som2nypost.com\/","name":"Som2ny Network","description":"Daily Deals","publisher":{"@id":"https:\/\/som2nypost.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/som2nypost.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/som2nypost.com\/#organization","name":"Som2ny Network","url":"https:\/\/som2nypost.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/som2nypost.com\/#\/schema\/logo\/image\/","url":"https:\/\/som2nypost.com\/wp-content\/uploads\/2026\/07\/4a0953c4-logo-300x86-1.png","contentUrl":"https:\/\/som2nypost.com\/wp-content\/uploads\/2026\/07\/4a0953c4-logo-300x86-1.png","width":300,"height":86,"caption":"Som2ny Network"},"image":{"@id":"https:\/\/som2nypost.com\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/som2nypost.com\/#\/schema\/person\/a66cfe5cdcbceba9b5562fe085bcaba4","name":"admin","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/som2nypost.com\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/729ae85bf62b9917e93538db2f2688ca?s=96&r=g&default=https%3A%2F%2Fsom2nypost.com%2Fwp-content%2Fplugins%2Fbuddypress-first-letter-avatar%2Fimages%2Fdefault%2F96%2Flatin_a.png","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/729ae85bf62b9917e93538db2f2688ca?s=96&r=g&default=https%3A%2F%2Fsom2nypost.com%2Fwp-content%2Fplugins%2Fbuddypress-first-letter-avatar%2Fimages%2Fdefault%2F96%2Flatin_a.png","caption":"admin"},"sameAs":["https:\/\/som2nypost.com"],"url":"https:\/\/som2nypost.com\/?author=1"}]}},"_links":{"self":[{"href":"https:\/\/som2nypost.com\/index.php?rest_route=\/wp\/v2\/posts\/163714","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/som2nypost.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/som2nypost.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/som2nypost.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/som2nypost.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=163714"}],"version-history":[{"count":0,"href":"https:\/\/som2nypost.com\/index.php?rest_route=\/wp\/v2\/posts\/163714\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/som2nypost.com\/index.php?rest_route=\/wp\/v2\/media\/163715"}],"wp:attachment":[{"href":"https:\/\/som2nypost.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=163714"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/som2nypost.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=163714"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/som2nypost.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=163714"},{"taxonomy":"dealstore","embeddable":true,"href":"https:\/\/som2nypost.com\/index.php?rest_route=%2Fwp%2Fv2%2Fdealstore&post=163714"},{"taxonomy":"offerexpiration","embeddable":true,"href":"https:\/\/som2nypost.com\/index.php?rest_route=%2Fwp%2Fv2%2Fofferexpiration&post=163714"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}