Sergei Basharov Sergei Basharov - 1 year ago 84
Javascript Question

Why 1 * new Date() instead of new Date().getTime() in GA snippet?

I am inserting GA snippet in my TypeScript code and seeing this:

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

TypeScript compiler complains that new Date() must be number or any, but not Date.

I turned this into this:

i[r]['l'] = new Date().getTime();

Which leads to the same result.

If the priority is to reduce the size, then I find this even more compact giving the same result:

i[r]['l'] = +new Date();

I have no idea why that smart-ass variant with implicit casting is used.

Is there anything hidden I don't understand or is it just guys want to look smarter? Is it to make it shorter in length?

Answer Source

Is there anything hidden I don't understand...

Nope, it's absolutely, 100% just to make it shorter in length.

In fact, if you look at the newest recommend snippet, it uses just +new Date, which is two bytes shorter than your +new Date() version:

<script>||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
    ga('create', 'UA-XXXXX-Y', 'auto');
    ga('send', 'pageview');
<script async src=''> </script>

It's true that a lot of linters and code build tools will complain about these types of practices, and for good reason. You probably shouldn't be using clever tricks like this in your source code because they're harder to read, not always clear on their intent, confusing, etc.

However, almost every minifier out there does use them to produce the most efficient code, and there's absolutely nothing technically wrong with them.

The point is you should write readable code and then depend on a minifier/compiler to make it as small and efficient as possible.

Google Analytics, however, cannot just assume that everyone who consumes their snippet will run it through a minifier, so it gives developers the snippet pre-minified.

The most common way to deal with including pre-minified code in your source files and avoid linter/compiler warnings is to ignore the entire block, a feature almost every linter offers.

For example, with ESLint, you can do this (something I see in a lot of people's source code around their Google Analytics snippet) by placing a comment directly before and after the block to ignore:

/*eslint-disable */||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
ga('create', 'UA-XXXXX-Y', 'auto');
ga('send', 'pageview');
/*eslint-enable */
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download