Comparing these strings:
{}[0]
[][0]
void 0
Why does Closure Compiler generate
void 0
when it could generate
[][0]
or
{}[0]
or even
[].a
as torazaburo mentioned which are 1 character shorter?
Minimum code size isn't the only goal of the Closure compiler. Another goal (I assume) is to generate code that is as fast as the original.
void 0
is likely to be faster across various JavaScript runtimes. It doesn't have to construct an object or array and dereference a nonexistent property.
A JavaScript runtime engine could possibly optimize away the {}[0]
or [][0]
, but why would the Closure compiler want to depend on that? If those don't get optimized away, they would be significantly slower than void 0
.
Keep in mind that JavaScript code is usually downloaded in compressed form, and if void 0
appears in multiple places they are likely to get compressed out.
Also see Blaise's answer for another good reason not to use {}[0]
or [][0]
.
{}[0]
doesn't (always? see comments) return undefined, and [][0]
could in theory return something other than undefined since you can override Array constructors/getters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With