Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the need for if(0) and if(1)

Look at this piece for code in ArcGIS 3.0 for javascript. https://serverapi.arcgisonline.com/jsapi/arcgis/?v=3.0

Inside there is "if(0)" and "if(1)", why is there a need for this? Isn't if(0) always false and if(1) always true?

like image 641
yeeen Avatar asked Jul 06 '12 02:07

yeeen


1 Answers

The Dojo build tools are what does that (under given build options), but not for obfuscation. If you look at non-built dojo.js and corresponding built dojo.js.uncompressed.js files, you can see that the build tool is replacing has("somefeature") calls with hardwired true/false tests. As noticed, this can and does create unreachable code. Why do this? Because then a smart optimizing compiler (e.g. Google Closure) can prune all that dead code out, resulting in a smaller file (sometimes MUCH smaller...that's the point).

Conceptually, it goes something like this:

  1. Non-built code has "kitchen sink" with dynamically-evaluated has() calls.
  2. You configure build profile with options indicating what you do/don't want in your custom build.
  3. Build process substitutes dynamic has() calls [for corresponding build options] with hardwired true/false tests (or better way to look at it is in/out tests).
  4. Closure compiler removes the "out" code during minification.

Check out current "Dojo Build System" documentation and http://jamesthom.as/blog/2012/08/03/finding-nano/ for more info. Also, here's a good low/code-level description of this process.

P.S. "if(0)/if(1)" isn't really obfuscation...kinda the opposite. If someone wanted to confuse, they'd more likely have "if(a)...if(b)...if(c)..." with vars set far, far away. However, minifiers produce more obfuscated code than that on their own. Check out dojo.js source before and after it's been run through Closure; the end product bears little resemblance to original.

like image 62
RandomActOfCoding Avatar answered Nov 15 '22 12:11

RandomActOfCoding