jamiestroud69
jamiestroud69

Reputation: 277

Google Analytics Validation: Unexpected '1'

I've tried to get Google Analytics to validate through http://codebeautify.org/jsvalidate and there's just 1 error I get: Unexpected '1'. It occurs on this line:

i[r].l = 1 * new Date();

Isn't the 1 * redundant? Why does GA have that? Is it safe to remove that part of the code? Just in case you want it, here's my full code:

/*global document, ga, window */
(function (i, s, o, g, r, a, m) {
    'use strict';
    i.GoogleAnalyticsObject = r;
    i[r] = i[r] || function () {
        i[r].q = i[r].q || [];
        i[r].q.push(arguments);
    };
    i[r].l = 1 * new Date();
    a = s.createElement(o);
    m = s.getElementsByTagName(o)[0];
    a.async = 1;
    a.src = g;
    m.parentNode.insertBefore(a, m);
}
(window, document, 'script', '//google-analytics.com/analytics.js', 'ga'));
ga('create', 'UA-XXXXXXXX-X', 'auto');
ga('require', 'displayfeatures');
ga('send', 'pageview');

Upvotes: 3

Views: 76

Answers (2)

vesperknight
vesperknight

Reputation: 770

As explained in the below question "Multiplication (or any arithmetic operation) causes a Date object to be converted to a number for the sake of evaluating the expression"

As odd as it seems to be multiplying a new Date object by an integer, this is what I would qualify as a quirk of javascript. Doing "1 * new Date()" is the equivalent of using .getTime().

The code is fine, the reason you are getting an error is because the parser from http://codebeautify.org/jsvalidate doesn't support this quirk.

You can test this easily by opening your console right now and typing console.log(1 * new Date()); You'll get the number of milliseconds since 1 January 1970. But if you paste that same one-liner of code in your validator it will throw the same error.

Multiplication with date object - javascript

Upvotes: 3

allu
allu

Reputation: 381

Actually there's a difference between new Date() and 1 * new Date():

new Date() returns the date object and 1 * new Date() returns the timestamp in milliseconds. Try them out!

var date = 1 * new Date();
var date2 = new Date();

alert("milliseconds: " + date + " and object: " + date2);

So I wouldn't remove the 1 *, because it seems GA uses that millisecond timestamp. Leave it as it is.

Upvotes: 2

Related Questions