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
In JavaScript the datatype of a variable depends upon the value it has currently stored. For example:
var _gaq; // _gaq is undefined
_gaq = 50; // Now _gaq has become a Number
_gaq= "Yap"; // 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.
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
A variable can store only one value at a time. If you want a variable to store more than one value at a time, then you need to use a special variable called ' array '.
An 'array' is made up of one or more elements. These elements can be
- strings (like 'hello'),
- numeric values (like 10),
- undefined values,
- boolean values (like true, false), other arrays or objects.
Arrays can contains elements of different data types
a1=["hi there", 10, 25, 26, "good bye"];
a2=["hi", "good bye", 10, 25, 26];
data layer which contains two elements
<script>
`dataLayer = [{ 'pageCategory': 'Statistics', 'visitorType': 'high-value' }];`
</script>
To improve readability you can re-write the data layer as:
<script>
dataLayer = [{
'pageCategory': 'Statistics',
'visitorType': 'high-value'
}];
</script>
Data layer variables are also known as data layer messages .
'window.dataLayer.push()' is the same as the 'dataLayer.push()' method but with an added advantage.
Using the ‘window’ prefix is that you can avoid conflict with any local JavaScript array variable that uses the ‘dataLayer’ name.
<script>
window.dataLayer.push({'pageCategory': 'Statistics','visitorType':
'high-value'});
</script>
I use JavaScript for analytics tracking to collect data.