Wednesday, January 30, 2013

The pattern of using fake functions parameters instead of var declaration in JavaScript

Many JS geeks making bazaar tricks to shrink the code as much as possible. While it makes the code readability worse and as result less reliable, it pays back with saving a byte or two making them proud.

There is my attempt to recover the damage by balancing it with some benefits.

sample 1 function(par1, par2, var1, var2, var3,i,j,x,y,z,k,w,n,m)

par1, par2, - Using parameters is out of scope of this article, just a note on the good habit to keep them read-only.

var1, var2, var3 - the local variables which are usually declared with var:

sample 2 var var1, var2, var3;
The good thing about such kind of declaration that along with declaring the variable it could be initialized.
IMO it is bad to have any uninitialized variable. Which means no ahead-declaration. The variable should be declared in place where it used and all initialization data are available:

sample 3 for( var x=0...)
for( var y=x ... )

But scripting guys do that all over thinking of saving bytes for "var " string and replacing with list of variables(as in #2, #4):
sample 4 var x,y;
for( x=0...)
for( y=0 ... )

5 more bytes ('var ' and ';')could be taken away by having local variable declared as function parameters:

sample 5 function (x,y)
for( x=0...)
for( y=0 ... )
The list of useful side effect will appear:
  1. shrinking the code footprint
  2. no global scope variables mistakenly assigned(#6)
    sample 6 function ()// no x is declared in the function
    for( x=0...) // here the global scope 'x' assigned
  3. questionable but will be loved by scripters(yuck) - declaring of all variables in single comma-separated list.

To prevent potentially missing declaration variables usually used in local scope (i,j,o,r,d,x,y,z,k,w,n,m) could be listed in complex functions as the safeguard.
The compilers could do the optimization quite well. Not sure whether relocation of variable declaration into function parameters is an option there.

No comments:

Post a Comment