Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning JavaScript primitives to their named equivalent variable like "constants"

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™

like image 569
Tristan Avatar asked Jan 05 '12 17:01

Tristan


3 Answers

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:

  • jQuery Anti-Patterns for Performance & Compression (slide 46)

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.

Paul Irish Anti-patterns slide 55

like image 163
Christian C. Salvadó Avatar answered Nov 08 '22 12:11

Christian C. Salvadó


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.

like image 40
dgvid Avatar answered Nov 08 '22 12:11

dgvid


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!

like image 37
Mike Christensen Avatar answered Nov 08 '22 14:11

Mike Christensen