Search code examples
google-analyticsgoogle-tag-manager

Can I replace dataLayer.push() with gtag()?


While trying to implement and understand the use of Google Tag Manager and Google Analytics I was wondering why there is talk about dataLayer.push() in some places while gtag() is used for similar operations in other places. They seems to be serving the same purpose even though the result is not exactly the same.

gtag() is defined as:

function gtag(){dataLayer.push(arguments)};

If I try the code I get a wrapping Arguments-object when using gtag. So I understand that there is a difference, but does this matter and should they be used for different purposes?

> dataLayer = []
> dataLayer.push({'event','login'})
[{'event','login'}]
> dataLayer = []
> gtag({'event','login'})
[Arguments({'event','login'})]

When should either one of them be used or could I resolve to only using one of them?


Solution

  • Well, there is no difference. gtag() is just a wrapper JS function around dataLayer.push(). However, gtag is preferable.

    The reason for using gtag is to avoid any action that might pollute or change data inside dataLayer object by accident, which might affect analytic data.

    Technically, they're the same, and you can use either ways.

    Personally, when tagging events, I usually create my own function:

    // definition
    function gevent(name, data) { 
        gtag('event', name, data);
    }
    
    // sample
    gevent('level_up', { userId: 123, prevLevel: 12, currLevel: 13 });
    gevent('logout', { userId: 123 });