Beginners guide to JavaScript for Google Analytics


JavaScript is the most popular programming language in the world. It is easy to learn (thus wide spread adoption), client side (thus very fast, no server side processing) and defacto language of web browsers (thus dubbed as the language of the web).


Why learn JavaScript?

Every analyst need to have two strong core skills in order to excel in the field of digital analytics. One is statistics and the other is JavaScript.

You need the knowledge of statistics in order to interpret the data accurately. You need to know JavaScript in order to get the data you want to analyse.

Statistics help you with data interpretation and JavaScript help you with data collection.

So if you are good in data interpretation but weak in data collection, you will always have to rely on a third party for your data collection needs. Unless your data requirements are met, you are stuck. You can’t move forward with your analysis because you don’t have the data to analyze.

You can’t assess the quality of data because you don’t understand how the data was collected. You need to work with whatever data you have got. Pretty helpless state.

Conversely, if you are strong in data collection but weak in data interpretation you won’t be able to improve the business bottomline. You have all the data you need but you don’t know how to use and interpret it correctly.

So it won’t be an exaggeration to say that Statistics and JavaScript are like the two legs of a web analyst. You need both legs in order to stand and run in the field of Web Analytics.

With just one leg you have got only two options: either hop or use a developer as a crutch all your working life. Both of these situations are undesirable and avoidable.

That’s why I cover both data interpretation and data collection issues on this blog. I strive to be good in both of these areas and expect you to do the same.

But why JavaScript and not any other programming language?

JavaScript is the most useful programming language for a web analyst.

All the measurement and marketing tags whether it is Google Analytics tracking code, ecommerce tracking code, event tracking code or Google Adwords conversion tracking code are written in JavaScript.

You need good working knowledge of JavaScript in order to implement:

#1 Ecommerce tracking
#2 Event tracking
#3 Phone Call Tracking
#4 Scroll Tracking

#5 Video Tracking
#6 Social Interactions Tracking
#7 Enhanced ecommerce tracking
#8 Cross domain tracking

and just about any tracking in Google Analytics.

Google Analytics tracking code is a JavaScript snippet. analytics.js library used by Google Analytics is a JavaScript file. Without JavaScript there will be no Google Analytics.


Role of JavaScript in maintaining a web document

where javascript fits

The three most important scripting languages which are widely used to create a web document are: HTML, CSS and JavaScript.

HTML (or Hyper Text Markup Language) is used to develop text content of a web document.

CSS (or Cascading Stylesheet) is used to control the layout and formatting of the text developed through HTML.

JavaScript is used to control the behaviour of HTML and CSS elements, users and web browsers.

These three scripting languages together create the modern web page which we see today.

We need to learn to keep the HTML, CSS and JavaScript code separated as much as possible on a web page by storing them in different files. What that means is that all CSS code should be stored in a CSS file and all the JavaScript code should be stored in a JavaScript file.

Often web pages contain all of these three different types of codes together and this is where the problem starts.

When you mix all of these three different types of codes together it becomes difficult to understand, diagnose, reuse and maintain a piece of code.


Methods to add JavaScript to HTML

There are three methods to add JavaScript code to a HTML document:

#1 Inline JavaScript

#2 Embedded JavaScript

#3 External JavaScript

Inline JavaScript

It is the JavaScript added to an HTML tag. For example:

<a onClick=”ga(‘send’, ‘social’, ‘Linkedin’,’Share’,window.location.href);“>….</a>

Here the text in bold is a JavaScript statement. You need an event handler like ‘onClick’ in order to use inline JavaScript.


Embedded JavaScript

It is the JavaScript added to a HTML document using the <script> tag which doesn’t contain the ‘src’ attribute. For example:

(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),

ga(‘create’, ‘UA-XXXX-Y’, ‘auto’);
ga(‘send’, ‘pageview’);


All the bold text is the JavaScript code. As you can see the Google Analytics tracking code that you copy-paste on each web page is actually embedded JavaScript.

You need to use script tags in order to use embedded JavaScript. JavaScript code placed outside the script tag will not execute.

Note: Every <script> tag must have the closing </script> tag and you can place script tags anywhere in the head or body section of a HTML document.


External JavaScript

It is the JavaScript added to a HTML document using the <script> tag which contains the ‘src’ attribute. For example:

<script type=”text/javascript” src=”myscript.js“></script>

Here all the JavaScript code is stored in an external JavaScript file and this file is called via the <script> tag.

External JavaScript is the recommended method to add JavaScript to a HTML document. Avoid using inline and embedded JavaScript wherever possible. There are three big advantages of using external JavaScript:

#1 Your JavaScript code does not interfere with other JavaScript code added to the same page and thus enable unobtrusive scripting.

#2 It becomes easier to maintain, debug, understand and reuse JavaScript code

#3 Cached JavaScript files can speed up page loads.


JavaScript statements

A JavaScript statement is an instruction which is executed by a web browser. Following is an example of JavaScript statement:

ga(‘create’, ‘UA-XXXX-Y’, ‘auto’);

Another example of JavaScript statement:

ga(‘send’, ‘pageview’);

The Google Analytics tracking code that you use so often is made up of bunch of JavaScript statements:

javascript statements

Each JavaScript statement must end with a semicolon ;

So following code is not valid:

missing semicolon

This is the correct code:

ga(‘create’, ‘UA-XXXX-Y’, ‘auto’);
ga(‘send’, ‘pageview’);

This missing semicolon error may look trivial but it can easily create a hard to diagnose tracking issue. This is because it is not very easy to spot a tiny missing semicolon in a big piece of code.


Order of execution of JavaScript statements

JavaScript statements are executed in the order in which they are written. By default they are executed from top to bottom and from left to right.

order of execution

Since JavaScript statements are executed from top to bottom, the following JavaScript statement in Google Analytics: ga(‘create’, ‘UA-XXXX-Y’, ‘auto’); will execute before the statement ga(‘send’, ‘pageview’);

The order of execution is as important as the code itself. If you change the order of JavaScript statements, your code will start behaving differently or may stop working. For example:

change in the order

Here I have changed the order of the last two JavaScript statements in the Google Analytics tracking code.

The second last statement ga(‘send’, ‘pageview’); is the instruction to send pageview data to Google Analytics server. The last statement ga(‘create’, ‘UA-XXXX-Y’, ‘auto’); is the instruction to create a tracking object and associate it with my web property.

Since I am trying to send pageview data to Google Analytics server before a tracking object is created, my Google Analytics tracking code will not work. So just by changing the order of JavaScript statements you can stop a code from working correctly.


JavaScript and white spaces

JavaScript ignores multiple white spaces. So the statement ga(‘create’, ‘UA-XXXX-Y’, ‘auto’); can be written as:

ga          (‘create’,              ‘UA-XXXX-Y’,        ‘auto’)       ;

or like this






Similarly the statement x=y+z; can be written as x = y + z ;

It is a good practice to put spaces around operators ( = + – * / ). Use extra white spaces to increase the readability of your JavaScript code.

In general, use of extra white spaces do not create any issue in your code. But there are some exceptions.

For example extra white spaces when used inside a string can cause problem:

extra white space

The web property ID used in your Google Analytics Tracking code is a string value (‘UA -XXXX-Y’).

When the web property ID contains extra spaces either before or after the ID then Google Analytics will not be able to recognize your web property ID and hence not be able to associate the tracking object with your web property.

As a result your Google Analytics tracking code will not be able to send any pageview and user data to GA server. This is another error which may look trivial but can easily create a hard to diagnose tracking issue.


Comments in JavaScript

Comments are used to add a note to a JavaScript code and to stop a JavaScript statement from being executed. There are two types of comments in JavaScript:

#1 single line comment
#2 multi line comment

Single-line comment begins with two forward slashes ( // ) and runs to the end of the line. For example:

single line comments

Here ‘creates a tracker’ and ‘sends a pageview’ are the single line comments added to the Google Analytics tracking code.

Note: Any text between // and the end of the line is ignored by JavaScript i.e. it is not executed.


A multi-line comment starts with /* and end with */ . For example:

multi line comment

Note: Any statements between /* and */ will not be executed by JavaScript. Forward slash is used whether a comment is single line or multi line comment.

Comments are commonly used to stop a statement from being executed during testing. For example following statement won’t execute as it has been made comment:

// setTimeout(“ga(‘send’,’event’,’Profitable Engagement’,’time on page more than 3 minutes’)”,180000);


JavaScript Variables

Variables are used to store values. Creating a variable in JavaScript is called ‘declaring a variable’.

You can declare a variable in JavaScript by using the keyword ‘var’.

For example:

var _gaq; // create a variable and name it _gaq

Another example:

var pageTracker; // create a variable and name it pageTracker

Note: It’s a good programming practice to declare all variables at the beginning of a script/code.

Use the assignment operator ‘=’ to assign a value to a variable.

For example:

var _gaq;
_gaq = _gaq || []; // assign the value ‘_gaq || [];’ to the variable _gaq

Another example:

var pageTracker;
pageTracker = _gat._getTracker(“UA-12345-1”); /* assign the value _gat._getTracker(“UA-12345-1”) to the variable pageTracker */

You can also declare a variable and assign it a value at the same time. For example:

var _gaq = _gaq || [];

Another example:

var pageTracker = _gat._getTracker(“UA-12345-1”);

To use the value of a variable, just use the variable name without surrounding it with quotes (single or double quotes).

For example:

var videoName= ‘superman vs Batman’;
ga(‘send’, ‘event’, ‘videos’, ‘play’,videoName);

If you enclose a variable name in quotes (single or double quotes) then it will become a string value. For example:

var videoName= ‘superman vs Batman’;
ga(‘send’, ‘event’, ‘videos’, ‘play’,’videoName’);

Here ‘videoName’ is a string value and not the variable we declared earlier. So this event tracking code will pass ‘videoName’ as event label instead of passing ‘superman vs Batman’ as event label.


Naming JavaScript Variables

There are 6 characteristics of variable names in JavaScript:

#1 Variable names are case sensitive.

#2 Variable names can be alphanumeric.

#3 No spaces are allowed in a variable name.

#4 No special characters (other than $ and underscore) are allowed in a variable name.

#5 A variable name can not begin with a number.

#6 A keyword can not be used as a variable name.

#1 Variable names are case sensitive.
For example, following are all different variables:

var pageTracker;
var pagetracker;
var PageTracker;

#2 Variable names can be alphanumeric.

var alpha23;

#3 No spaces are allowed in a variable name.


var first name = ‘Himanshu’; // not valid

#4 No special characters (other than $ and underscore) are allowed in a variable name.
For example:

var _gaq = “Peter”; // underscore is allowed in a variable name
var US$ = 1500; // dollar sign is allowed in variable name
var First-name= “anna”; // hyphen is not allowed in a variable name

#5 A variable name can not begin with a number.
For example:

var 23alpha; // not valid

#6 A keyword can not be used as a variable name (more about keywords later).


Best practices for creating variable names in JavaScript

#1 Use lower-case for variable names wherever possible.

#2 Use either underscore to separate each word in variable name or use camel casing.

For example:

var first_name = ‘Himanshu’;
var firstName= ‘Himanshu’;

Note: In a camel case we capitalize the first letter of each word except the first word.


JavaScript Keywords

A keyword (or identifier) is a reserved word which carry special meaning.

Following are some examples of keywords in JavaScript:

  1. var
  2. function
  3. return
  4. for
  5. true
  6. false
  7. null
  8. undefined
  9. if


var function; // not valid as ‘function’ is a keyword.
var positiveResult = true; // valid
var negativeResult = false; // valid

true and false are keywords in JavaScript. They are also boolean values. So you don’t need to put any quote marks around them.

If you put quote marks around them then they will become string values. For example:

ga(‘create’, ‘UA-XXXX-Y’, {‘allowLinker’: true}); // valid
ga(‘create’, ‘UA-XXXX-Y’, {‘allowLinker’: ‘true’}); /* not valid because ‘true’ is a string value and allowLinker doesn’t accept string */

Note: All JavaScript identifiers are case sensitive. So JavaScript does not interpret VAR or Var as the keyword var:

Var _gaq; // not valid
VAr _gaq; // not valid
VAR _gaq; // not valid
var _gaq; // valid


JavaScript Values

A JavaScript variable can store value of any data type. It can store:

  1. Numeric value (whole number, decimal number)
  2. String value
  3. Boolean value
  4. Undefined value
  5. null value
  6. Array
  7. Multidimensional array
  8. Object
  9. Array of Objects
  10. Other variables

For example:

Numeric Values

var a = 3;
a = 3.14159265;
a = -3;
a = -3.14159265;


a =’himanshu’;
a = “sharma”;

Boolean Values

a = true;
a = false;

Undefined value

a= undefined;

Null value

a = null;


a = [1,2,3];
a= [[‘name’,’john’],[‘age’,20]];


a = {‘age’:24};
var dataLayer = [{‘name’:’john’,’age’:23}, {‘name’:’ash’,’age’:42}];

Other Variable

var half = 12;
var full = half * 2;


In JavaScript the datatype of a variable depends upon the value it has currently stored.

For example:

var _gaq; // _gaq is undefined
_gaq = 5; // Now _gaq has become a Number
_gaq= “John”; // Now _gaq has become a String
_gaq =true; // Now _gaq has become a boolean
_gaq=[]; // Now _gaq has become an array
_gaq ={}; // Now _gaq has become an object

Because of this flexibility in data types, JavaScript programs are highly prone to errors.


Strings in JavaScript

A string is a series of characters of any length.

String must be enclosed by single or double quote marks. For example:

var name = ‘Himanshu sharma’;
var name2 = “John lewis”;
var address = “28 station road”;
var emailAddress= ‘crazynitch[@]gmail[.]com’;

Note: Any character available on a keyboard can be used in a string including white spaces.

You can use quotes inside a string, as long as they don’t match the quotes surrounding the string.


var comment = “It’s alright”; // valid
var wrestlerName = “Hunter ‘Hearst’ Helmsley”; // valid
ga(‘send’, ‘event’, {
‘eventCategory’: ‘Wrestling’,
‘eventAction’: ‘Heavy weight”,
‘eventLabel’: wrestlerName


ga(‘send’, ‘event’, {
‘eventCategory’: ‘Wrestling’,
‘eventAction’: ‘Heavy weight”,
‘eventLabel’: ‘Hunter “Hearst” Helmsley’ // valid


ga(‘send’, ‘event’, {
‘eventCategory’: ‘Wrestling’,
‘eventAction’: ‘Heavy weight”,
‘eventLabel’: ‘Hunter ‘Hearst’ Helmsley’ /* not valid because inner quotes match with surrounding quotes */


var hhh = “Hunter “Hearst” Helmsley”; /* not valid because inner quotes match with surrounding quotes */

If you want to use quotes inside a string which match the quotes surrounding the string then you need to use back slash \ (also known as escaping character).

For example:

var hhh = “Hunter \”Hearst\” Helmsley”; // valid
hhh = ‘Hunter \’Hearst \’ Helmsley’; // valid

If you enclose a number in quotes (either single or double quotes), it will be treated as string by JavaScript.

For example:

ga(‘send’, ‘event’, ‘videos’, ‘play’, ‘Superman’, ’40’); /* not valid because ’40’ is a string value and not number */
ga(‘send’, ‘event’, ‘videos’, ‘play’, ‘Superman’, 40); // valid because 40 is a number

Needless to say, you need to be careful with how you use the quotes in your JavaScript code. You can make a perfectly valid number a string just by surrounding it with quotes.


JavaScript Arrays and Objects

An array is a special variable which can store multiple elements of same or different data types at a time.

These elements can be strings, numeric values, undefined values, boolean value, other arrays or objects.

javascript array

You can create an array in JavaScript by using the ‘new Array()’ function or via array literal notation [].

For example:

var cars = new Array();


var cars = [];

The datalayer that you use in Google Tag Manager is also a JavaScript array:

dataLayer = []; // empty data layer

Object is also a special variable which has got properties and methods.javascript object

object enhanced ecommerce

Syntax for creating objects in JavaScript:

ObjectName={‘property1’:value1, ‘property2′:value2, …..’propertyN’:valueN};

Here property can be any string or identifier.

The datalayer that you use in Google Tag Manager is a JavaScript array of one or more objects. For example:

dataLayer = [{

‘pageCategory’: ‘Statistics’,

‘visitorType’: ‘high-value’


I have explained both Arrays and Objects in great detail in this article: Google Tag Manager Data Layer explained like never before. So check it out.


Functions in JavaScript

JavaScript function is a block of code which performs a particular task when it is executed.

A JavaScript function can not execute on its own. It needs to be called in order to be executed.  We use the keyword ‘function‘ to create a JavaScript function.

Following is the syntax for creating a function in JavaScript:

function <functionName>(parameter1, parameter2,….) {
Java Script Statement1
Java Script Statement2
Java Script StatementN


Here, Parameters are the names we list when defining a function.

Arguments are the values we pass when calling a function.

For example in the Google Analytics tracking code the names i,s,o,g,r,a,m are parameters and the values ‘window’, ‘document’, ‘script’, ‘//’ and ‘ga’ are arguments:

parameters arguments

Note: Using parameters and arguments is optional.


Following are the examples of functions used in tracking Twitter Social Interactions (clicks, tweets, follows) in Google Analytics:

// Define Call Back Functions
function clickEventToAnalytics() {
ga(‘send’, ‘social’, ‘Twitter’, ‘Click’, window.location.href);

function tweetIntentToAnalytics() {
ga(‘send’, ‘social’, ‘Twitter’, ‘Tweet’, window.location.href);

function retweetIntentToAnalytics() {
ga(‘send’, ‘social’, ‘Twitter’, ‘Retweet’, window.location.href);

function followIntentToAnalytics() {
ga(‘send’, ‘social’, ‘Twitter’, ‘Follow’, window.location.href);

Note: Rules for creating function names is same as the rules for creating variable names.


Google Analytics ‘ga’ function

Google Analytics uses it own in-built function known as the ‘ga’.

This function does almost every task in Google Analytics, whether it is creating a tracking object, sending pageview data, sending event data, ecommerce data etc.

ga function


The first argument of ‘ga’ function is a Google Analytics command (like ‘create’, ‘require’, ‘send’ etc)

The second and subsequent arguments depend upon the Google Analytics command being used:

ga function2

By passing different arguments to the ‘ga’ function, you can carry out different tasks in Google Analytics. For example:

ga(‘create’, ‘UA-XXXX-Y’, ‘auto’); // create a tracking object

ga(‘send’, ‘pageview’); // send pageview data to GA server

ga(‘send’, ‘event’, ‘videos’, ‘play’,’videoName’); // send event tracking data

ga(‘require’, ‘ecommerce’); // load ecommerce plugin

ga(‘require’, ‘ec’); // load the enhanced ecommerce plugin

ga(‘linker:autoLink’, [‘’, ‘’]); // define which domains to auto link

ga(‘ec:addImpression’, // send product impression data
‘id’: ‘P12345’,
‘name’: ‘Android Warhol T-Shirt’,
‘category’: ‘Apparel/T-Shirts’,
‘brand’: ‘Google’,
‘variant’: ‘Black’,
‘list’: ‘Search Results’,
‘position’: 1,
‘dimension1’: ‘Member’

Since functions names follow the same rules for naming variables, they are also case sensitive.

So if you use GA as in:

GA (‘create’, ‘UA-XXXX-Y’, ‘auto’); // not valid statement

Ga (‘create’, ‘UA-XXXX-Y’, ‘auto’); // not valid statement

ga (‘create’, ‘UA-XXXX-Y’, ‘auto’); // valid statement

Each function in Google Analytics has fixed number of parameters which are allowed. If you try to add more parameters than allowed then this will cause tracking issues. For example:

When the ‘ga’ function is used to send ‘event’ data, then only four values are allowed: ‘event category’, ‘event action’, ‘event label’ and ‘event value’. Consequently following statement is not valid as it contains more parameters than allowed:

ga(‘send’, ‘event’’, ‘videos’, ‘play’,40, ‘full speed’); // not valid statement


Each function in Google Analytics accept arguments of certain data type. So if you add an argument which is of different data type, then this will cause tracking issues. For example:

wrong data type

Similarly, each function in Google Analytics has fixed number of required parameters, the parameters which you have to enter for a given method.

If you skip one of the required parameters then this can make the tracked data unreliable or your tracking may stop working. For example ‘Transaction ID’ is a required parameter when measuring product impressions in enhanced ecommerce tracking.

So if this parameter is not passed then the tracking code won’t work:

product id is missing

Other important points to keep in mind regarding Google Analytics Functions:

#1 Use correct syntax for all the functions in Google Analytics.

For example the names of all the functions (methods) in classic Google Analytics (ga.js) should begin with underscore _ . Otherwise the functions will not execute and tracking will not work as intended. For example use _trackPageView instead of trackPageView. In case of universal analyticsuse ga instead of GA.


#2 Use only the active methods/functions found in the Google Analytics Library

Google Analytics depreciate certain methods from time to time. Methods once depreciated should no longer be used as they can negatively affect data quality. Review your Google Analytics Tracking codes periodically and make sure that you use only active methods.

You can find the list of all active methods for Universal Analytics from here: 

You can find the list of all active methods for Classic Google Analytics from here:


#3 Never add quotes (either single or double quotes) to a function argument which should not be quoted like numbers, boolean values, functions, arrays, objects, variable names etc.

Use quotes only when you want a value to be interpreted as string. Otherwise Google Analytics may incorrectly record data or fail to record data.


#4 Always refer to the Official Google Analytics Developers documentation

Whenever you are customizing your Google Analytics tracking code or implementing a certain type of GA tracking, always refer to the official GA developers documentation to make sure that you are using the correct syntax for your code.

GA developers documentation for Universal Analytics:

GA developers documentation for Classic Google Analytics:


Google Analytics Tracking Code

There are few things about Google Analytics tracking code which you need to remember in order to prevent tracking issues:

#1 Make sure every web page on your website contains Google Analytics tracking code (GATC). Otherwise you will get self referral issues.

#2 Avoid customizing the GATC if you don’t know what you are doing. You are most likely to break the code and the code once broken will stop working. Even a missing semicolon can break the code.

#3 Never copy paste the GATC from a word document as it can change the quotation marks in your tracking code which may stop the code from working.

#4 If the GATC on a page is not the asynchronous version of the tracking code snippet then the reported data could be unreliable. So you need to upgrade to the asynchronous version of the tracking code.

#5 There are many versions of GATC: urchin.js (oldest version), ga.js, dc.js and analytics.js (latest version). Installing multiple versions of the google analytics tracking code on a page can inflate pageview and users data and make them unreliable. So always use only one version of google analytics tracking code on a page at a time.

#6 Keep the GATC inside the head section of a web page. This increases the likelihood that tracking beacon is sent before a user leaves the page.

#7 Make sure that you are using the correct GATC. Webmasters who manage mutiple websites, sometimes add the GATC of another website.

#8 Even if you place Google Analytics tracking code in an external script file, Google Analytics will continue to collect analytics data.

#9 Each time GATC is executed, it sends an HTTP response to the GA server. But when GATC is not executed, no HTTP response is sent.

So if you see an error message ‘No HTTP response detected’ then it means either your browser is using some extension which doesn’t let the GATC from being executed or there is some syntax error in GATC.


Announcement about my new books

Maths and Stats for Web Analytics and Conversion Optimization
This expert guide will teach you how to leverage the knowledge of maths and statistics in order to accurately interpret data and take actions, which can quickly improve the bottom-line of your online business.

Master the Essentials of Email Marketing Analytics
This book focuses solely on the ‘analytics’ that power your email marketing optimization program and will help you dramatically reduce your cost per acquisition and increase marketing ROI by tracking the performance of the various KPIs and metrics used for email marketing.

Attribution Modelling in Google Analytics and Beyond
Attribution modelling is the process of determining the most effective marketing channels for investment. This book has been written to help you implement attribution modelling. It will teach you how to leverage the knowledge of attribution modelling in order to allocate marketing budget and understand buying behaviour.

Himanshu Sharma

Certified web analyst and founder of

My name is Himanshu Sharma and I help businesses find and fix their Google Analytics and conversion issues.
If you have any questions or comments please contact me.

  • Over eleven years' experience in SEO, PPC and web analytics
  • Certified web analyst (master level) from
  • Google Analytics certified
  • Google AdWords certified
  • Nominated for Digital Analytics Association Award for Excellence
  • Bachelors degree in Internet Science
  • Founder of and

I am also the author of three books: