Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the arguments variable in the gtag snippet?

Open question. Looking at the Global site tag (gtag.js) snippet I don't really understand the use of the arguments variable.

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=GA_TRACKING_ID"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'GA_TRACKING_ID');
</script>

What does it mean exactly? What is the use of dataLayer.push(arguments) here?

Thanks!

like image 309
Simon Breton Avatar asked Jul 24 '18 17:07

Simon Breton


1 Answers

That's nothing special to Analytics or gtag. It's just a standard Javascript object. It represent all the arguments passed to functions.

What analytics is doing here is just pushing into the dataLayer an object with all the parameters passed to the gtag tag. This doesn't mean you can simply remove the gtag function and use the dataLayer directly because once the gtag.js file is loaded it can replace the gtag function with a different function that keeps the same interface.

From: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments

The arguments object is a local variable available within all (non-arrow) functions. You can refer to a function's arguments within the function by using the arguments object. This object contains an entry for each argument passed to the function, the first entry's index starting at 0. For example, if a function is passed three arguments, you can refer to them as follows:

arguments[0]
arguments[1]
arguments[2]
like image 104
Eduardo Avatar answered Oct 18 '22 18:10

Eduardo