🥳 You have completed all topics in the Handbook. Click here to claim your certificate!

2. JavaScript

JavaScript is the most important programming language for anyone working in technical marketing. It permeates all parts of the client-side experience, and in many cases it runs the corresponding server-side processes, too.

JavaScript is one of the most popular programming languages of the world.

Much of its popularity comes from its important role on the World Wide Web.

JavaScript joins the trifecta of HTML and CSS to provide the modern web experience, from creating dynamic web pages to running hybrid apps, from handling user interactions to running analytics collectors, and from being both the cause of and the solution to web performance issues.

From a programming perspective, JavaScript is something of a blank slate. Its roots are in the “C” family of languages (C, C++, Java…). However, it deviates enough from the stricter syntactic paradigms of these languages to make any type of comparisons counter-productive.

In this Topic, we’ll discuss some of JavaScript’s unique qualities from a technical marketing perspective. As such, we will barely scratch the surface of what can be done with JavaScript, especially in a full stack context.

Simmer’s JavaScript For Digital Marketers

If you are interested in learning the language (it should be well within your capabilities as a technical marketer), you should take a look at the (free) JavaScript course on freeCodeCamp as well as Simmer’s course JavaScript For Digital Marketers.

JavaScript controls the browsing experience

As we discussed in the Web Browser Chapter, JavaScript is largely responsible for producing the interactive experiences of modern websites.

While HTML and CSS are the basis for the visible layout of the page, JavaScript enables the experience of the web page, including things like:

  • Dynamically loading content upon user interaction
  • Handling and validating forms
  • Pop-ups and modals
  • Animating and enriching ordinary interactions such as clicks and scrolls

JavaScript offers interfaces and APIs for web developers to work with. With JavaScript, developers can assess, enrich, validate, and completely mutate web interactions that many users take for granted.

Example

Single-page apps are entirely controlled by JavaScript. When you click a link to navigate around the site, JavaScript blocks the link from redirecting the user to the linked page. Instead, the content is fetched dynamically from the web server and inserted on the page, yes, with JavaScript.

Google Tag Manager doesn’t work if JavaScript is disabled in the browser

Often, JavaScript is used to enrich the page experience. Naturally, whether scripting is actually “enriching” instead of “irritating” really depends on how discreet it is.

Example

The tooltips in this Handbook have been engineered with JavaScript. While there might have been a CSS-only way to do them, JavaScript gives more options for customization than a pure CSS approach.

In addition to these examples, JavaScript is also the language of the digital marketing world. Analytics trackers, advertising pixels, page performance optimizations, and consent management systems are all controlled (more or less) by JavaScript.

This proliferation of JavaScript is also problematic. JavaScript is often written in a very verbose way, and loading multiple files just to enrich the web experience can be detrimental to performance. For this reason, web browsers are slowly updating HTML and CSS to natively do some of the things that are today only enabled with JavaScript.

However, web standards are very slow to evolve, and lack of cross-browser support means that as long as these updates to HTML and CSS are not widespread, JavaScript still needs to enable the same use cases for unsupported browsers.

Ready for a quick break?

We really recommend you take a small brain break at this point. After that, let’s jump into the weeds with some JavaScript under-the-hood content!

Document Object Model

The main interface between JavaScript and the web page is called the Document Object Model.

When the web browser renders the HTML source file, it turns it into a tree structure. In this structure, individual HTML tags become elements (also known as nodes) that can be nested within each other.

Each element in this tree is accessible with JavaScript. You can use methods specifically designed for interacting with the DOM, and these methods allow you to…

  1. Select elements on the page
  2. Create, modify, and delete elements on the page
  3. Add listeners to elements that react to user interactions and other on-page events
  4. Climb up and down the DOM as you look for a specific element
  5. Access the element’s content, attributes, properties, and other metadata

If you look at this list and consider that every single thing a user sees or interacts with on a web page corresponds to a DOM element, you can understand how powerful JavaScript can be.

JavaScript’s ability to modify what the browser renders from the HTML source means that if you compare the page HTML source file itself with what is actually shown on the page, the two might be completely different.

Especially with single-page apps, the web server only returns the initial HTML source of the page load. As the user navigates the site, new content is loaded dynamically from the web server, but the HTML source of the page remains the same.

But even with “regular” sites, JavaScript can be used to heavily modify what was originally encoded in the page HTML.

Deep Dive

Google Tag Manager’s “magic” triggers

If you use a tag management system like Google Tag Manager, you might have marvelled at how easy it is to create a “Click trigger” that automatically fires your tags when the user clicks a specific element.

Well, under the hood GTM simply uses a DOM method to add a click listener to the web page, which then waits for the click event to happen. When the click happens, details about the event are inserted in to GTM’s Data Layer, from where they can fire and provide data for your tags.

// Basic example of how GTM's click triggers work:

// 1. Add the listener to the web page, and run a callback function
// when the click happens.
document.addEventListener('click', function(e) {

  // 2. Push details about the click target into dataLayer
  window.dataLayer = window.dataLayer || [];
  window.dataLayer.push({
    event: 'gtm.click', // The name of the click event
    'gtm.element': e.target, // The HTML element that was clicked
    'gtm.elementId': e.target.id || '', // The value of the "id" attribute or empty string
    'gtm.elementClasses': e.target.className || '', // The value of the "class" attribute or empty string
    'gtm.elementUrl': e.target.href || e.target.action || '', // The target URL of the element, or empty string
  });

});

When using Google Tag Manager, it might seem like magic. But under the hood, GTM is simply interacting with JavaScript APIs that would be available to you even without GTM.

Don’t miss this fact!

The Document Object Model (DOM) is the main way of interacting with the web page using JavaScript. As a technical marketer, the better you understand the machinations of the DOM, the better you can anticipate how your work will be able to coexist with complicated web pages.

Dangers of types and scopes

Unruly usage of JavaScript on a web page can also be detrimental to the page experience.

As mentioned above, JavaScript can be used to delete elements on the page. For example, if you were to run this code on any web page, you would delete all the content of the page:

// Don't run this code on a web page, please
document.removeChild(document.querySelector('html'));

But you would probably never even unintentionally run a piece of code like that unless you were being manipulated by someone pulling a prank on you.

However, there are less insidious ways of JavaScript throwing a wrench into the works.

JavaScript is loosely typed. This means that if you declare a variable, there’s no built-in mechanism that forces that variable to always have a certain type. This might lead you to inadvertently overwriting a variable with an unexpected type, which would then break any code that expects the type to be something specific.

For example, look at this:

// Google Tag Manager's dataLayer is defined as an array, as is expected.
window.dataLayer = [];

// Much later in the code, conflicting code overwrites dataLayer as a plain object.
window.dataLayer = {
  pageType: 'article'
};

// Which then results in all of Google Tag Manager's own instruments breaking:
window.dataLayer.push({
  event: 'pageChange'
});
// Uncaught TypeError: window.dataLayer.push is not a function

Because JavaScript doesn’t have type enforcement, nothing is stopping a programmer from rewriting the dataLayer array (that GTM expects) into something else. But as it’s no longer an array, all the native array methods that GTM relies on (such as dataLayer.push) fail because the overwritten dataLayer is no longer an array.

Another problem with JavaScript, particularly in the context of the web, is that it has two main scopes: global and local.

Globally scoped variables are available everywhere on the page. Any JavaScript running on the page can make use of them.

Locally scoped variables are only available in the function context where they are declared.

There’s a saying among JavaScript web developers: “Don’t pollute the global scope“. This means that unless absolutely necessary, always declare variables locally.

Why? Because sometimes when you have a scenario where a local variable would suffice and you instead use the global scope, you might end up overwriting the original, globally scoped variable.

// dataLayer is declared globally:
window.dataLayer = [];

// A function creates local scope:
function loadPage() {
  console.log('Page is loaded');
  
  // BAD! This overwrites the globally scoped dataLayer:
  dataLayer = {
    pageType: 'loaded'
  };
  
  // BETTER! The "var" keyword creates a new dataLayer variable that is locally scoped:
  var dataLayer = {
    pageType: 'loaded'
  };
  
  // BEST! This creates a locally scoped variable that doesn't have any conflict with the well-known dataLayer name:
  var customData = {
    pageType: 'loaded'
  };
}

The key takeaway here is that if you want to start producing custom code on web page, you need to be aware of these two quirks and the plethora of other JavaScript idiosyncrasies that might show up and decimate the entire browsing experience of your website.

This isn’t meant to scare you away from using JavaScript. But as a technical marketer, you might find yourself frequently offering code snippets and issuing requests for modifying on-page JavaScript. In these cases, you should be aware of best practices when it comes to coding, such as those that are extensively covered in Simmer’s JavaScript course.

Don’t miss this fact!

JavaScript’s relaxed approach to types and its division of global and local scope can really trip you up if you want to produce code on the site but don’t understand these concepts.

Debug JavaScript on the page

If you ever need to test, debug, or validate JavaScript on a web page, you need to familiarize yourself with the browser’s developer tools.

Google Chrome, for example, has an extremely powerful set of developer tools that you can open by pressing the F12 key on your keyboard.

For JavaScript debugging purposes, you’ll find the Elements panel and the Console panel most useful.

The Elements panel is where you can see the DOM in all its glory. You can search for elements, you can expand and contract the tree’s nodes, you can delete elements, you can edit them, and you can add new elements – all in the developer tools’ Elements panel without having to write a single line of JavaScript.

When debugging your JavaScript, the Elements panel can quickly ascertain whether a certain element exists on the page, for example. If you are trying to write code that relies on the existence of an element, it’s good to verify it actually does exist with this panel.

In the Elements panel, you can also edit the styles of any given element on the page, which is very useful if you want to test alternative approaches to styling your content.

The DOM element in the Elements panel corresponding to the visible content on the page

The Console panel is your best JavaScript debugging device, however. It lets you run any browser JavaScript in the context of the current page.

If you have code you want to test before running it through Google Tag Manager, for example, executing it in the browser’s JavaScript console is a great way to make sure it works as intended.

Any code you run in the JavaScript console can interact with the DOM in its current state. If the elements on the page change, you can run the code again and it will react with the updated state.

Page content is updated with DOM methods while in the developer tools’ JavaScript console

As a technical marketer, getting acquainted with the browser’s developer tools is a huge service to your professionalism.

You’ll be able to test, debug, and verify the impact of your marketing efforts before you need to escalate them to IT. You can execute your own code, update the source files of the site, and run full performance profiling tests on the web pages through your own, local browser environment.

At the same time, being an expert of developer tools only takes you so far. In the context of this Topic, your main job is to be aware of the devastating power and limitless capability of JavaScript. While you don’t need to know how to code a single line of JavaScript to be an adequate technical marketer, learning at least the basics of the language will go a long way into helping you break through professional plateaus and into opening new career paths for you.

Key takeaway #1: JavaScript is the language of the web browser

JavaScript is the third component to the trifecta of web design, complementing HTML and CSS as the language that enables the experience of the web page. When you interact with a web page in the browser, these interactions are fuelled by JavaScript. Things like dynamically loading content, form validation, pop-ups, modals, and animated clicks and scrolls are (almost always) generated by JavaScript. For a technical marketer, JavaScript is present in almost every aspect of their job, as the web browser is still the most important tool in the marketer’s arsenal.

Key takeaway #2: DOM is the dynamic representation of the web page

For a technical marketer, the most important piece of browser JavaScript to understand is the Document Object Model (DOM). It’s generated by the web browser from the source HTML and its linked resources (CSS, images, scripts…). It’s represented by a node tree, where individual HTML elements are all part of a nested tree structure. These elements, their position, and their individual styles can be manipulated with JavaScript. This is what enables the modern web browsing experience.

Key takeaway #3: Global and local scope

In addition to the DOM, another key aspect of JavaScript is the notion of “scope”. Fundamentally, JavaScript operates in two scopes: global and local. Global scope means that the variables and functions you declare are available globally – in any part of any JavaScript code running on the page. Local scope means that these are only available within the immediate context. Writing JavaScript in global scope is dangerous, because you risk overwriting similar variables or functions that were added to global scope by some other piece of code.

Quiz: JavaScript

Ready to test what you've learned? Dive into the quiz below!

1. Why is it dangerous to set variables in global scope?

2. What is the Document Object Model?

3. What are some of the things you can do with JavaScript?

Your score is

0%

What did you think about this topic?

Thanks for your feedback!
Next up

Unlock Premium Content

Simmer specializes in self-paced online courses for technical marketers. Take a look at our offering and enroll in one or more of our courses!

Online course

JavaScript For Digital Marketers

Check out our comprehensive online course to learn this necessary technical marketing skill!