I was looking at the source code to qTip 2 and saw the following:
// Munge the primitives - Paul Irish tip
var TRUE = true,
FALSE = false,
NULL = null;
I can't come up with a reason you should ever do this, and have a strong feeling that it would just encourage bad coding habits. Say a developer makes a typo in a Yoda condition like if (TRUE = someCondition())
, then TRUE
could very well end up actually meaning false
, or you might end up assigning someObject
to NULL
.
I guess I'm just wondering if there's some redeeming quality for this practice that I'm missing, or if this is just a plain old Bad Idea™
The goal of this is just to improve compression, Paul Irish himself calls it as an "Anti-Pattern".
He describes it as "Good for compression and scope chain traversal" on the following presentation:
On scope chain traversal, we won't see any improvement on literals as null
, false
, true
, since the scope chain is not inspected, they are just literals.
On other identifiers as undefined
or windows
the scope chain traversal is indeed inspected.
You could do this for the sake of code compression. For example, YUI Compressor is not going to touch true
and false
, but it could replace all occurrences of, for example, TRUE
with A
, saving four characters per occurrence. For example, before compression:
if (foo === null) {
bar = true;
}
After compression, assuming the compressor replaces TRUE
with a
and NULL
with c
:
if(foo===c){bar=a;}
Versus this, after compression with no "munging of primitives":
if(foo===null){bar=true;}
The bad-coding-habits danger that you quite correctly cite in your question may outweigh the small savings in additional compression. It depends on how desperate you are to save a few dozen or perhaps a few hundred bytes.
Personally, I would (almost) never do this. Too dangerous.
I believe this is recommended for compression.
These shortcut variables will be compressed when munged, resulting in smaller files. However, your noted drawbacks are most certainly valid points!
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