Why does the closure compiler generate void 0 instead of shorter alternatives?

Comparing these lines:

{}[0]
[][0]
void 0

      

Why Closure Compiler generates

void 0

      

when can it generate

[][0]

      

or

{}[0]

      

or even

[].a

      

as Torazaburo said which are 1 character shorter?

+3


source to share


2 answers


Minimum code size is not the only goal of the Closure compiler. Another goal (I suppose) is to generate code that is as fast as the original.

void 0

is likely to be faster in different JavaScript scenarios. It doesn't need to create an object or array and dereference a non-existent property.

The JavaScript runtime can optimize parameters {}[0]

or [][0]

, but why does the Closure compiler want to depend on this? If they are not optimized, they will be significantly slower than void 0

.



Keep in mind that JavaScript code is usually loaded in a compressed form, and if it void 0

appears in multiple places, they may be compressed.

Also see Blaise's answer for another reason not to use {}[0]

or [][0]

.

+4


source


{}[0]

does not return (always? see comments) return undefined, but [][0]

could theoretically return something other than undefined as you can override Array constructors / getters.



+3


source







All Articles