Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the pros and cons of passing *all* javascript variables (even undefined) as function arguments? [closed]

Let's take the Google Analytics Universal script as premise of the practice I am looking to clarify, validate and/or expand on:

<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (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','//www.google-analytics.com/analytics.js','ga');
</script>

Google has chosen to pass all variables as arguments instead of declaring them with var. The clear benefit in this case, is to minify the code to a maximum (avoiding the var keyword in scope and the = character repeats) with a and m being undefined... While it is common to pass an existing variable as argument, or an object into scope, passing undefined variables as argument to skip declaring them is quite unusual.

I am interesting in knowing whether there are known caveats with that approach. Particularly:

Does this use more or less memory, or is it equivalent to declared vars in the function scope?

Does it make any difference in regard to the garbage collector, and how so?

And does an increased or extensive amount of passed arguments to a function have any downsides in terms of performance?

Additional Notes: Please, NO GUESS ANSWER. I am not interested in opinion based answers. Also the question is not about passing object scope as already answered at: https://stackoverflow.com/a/4665324/1647538. So please don't answer for that particular aspect.

I am only looking for verifiable fact-based answers from javascript seasoned experts or browser implementors, with extensive knowledge of javascript compilers, and how garbage collectors work.

like image 912
hexalys Avatar asked Dec 19 '13 03:12

hexalys


1 Answers

Not sure about this case specifically, but injecting objects such as window and document rather than directly referencing them from inside of a function allows you to pass mock objects during unit testing.

like image 73
JPR Avatar answered Oct 30 '22 22:10

JPR