Search code examples
javascriptenumstypescriptiife

Enums in TypeScript: what is the JavaScript code doing?


The following TypeScript:

enum PrimaryColors { Red, Green, Blue };

Produces the following JavaScript:

var PrimaryColors;
(function (PrimaryColors) {
    PrimaryColors[PrimaryColors["Red"] = 0] = "Red";
    PrimaryColors[PrimaryColors["Green"] = 1] = "Green";
    PrimaryColors[PrimaryColors["Blue"] = 2] = "Blue";
})(PrimaryColors || (PrimaryColors = {}));
;

I am embarrassed to admit that I don't understand what the JavaScript is doing.
The function in parentheses is assigning string values using another assignment as the index/key. I have not seen anything like this before.
And what is the purpose of the (PrimaryColors || (PrimaryColors = {}) following the function?
If the answer is to learn JavaScript properly, I will readily accept it, provided it comes with a suggested source that clearly explains what I am seeing here.


Solution

  • I believe:

    PrimaryColors[PrimaryColors["Red"] = 0] = "Red";
    

    is equivalent to:

    PrimaryColors[0] = "Red";
    PrimaryColors["Red"] = 0;
    

    See this reference.

    The expression x = 7 is an example of the first type. This expression uses the = operator to assign the value seven to the variable x. The expression itself evaluates to seven.

    For example:

    console.log((x = 7));
    

    outputs:

    7
    

    Similarly:

    var x = {};
    console.log((x["hi"] = 7));
    

    Also outputs 7.


    As for the second thing, PrimaryColors is initially undefined.

    var x;
    console.log(x); // undefined
    

    In a boolean context, undefined evaluates to false:

    console.log(!undefined); // true
    console.log(!!undefined); // false
    

    Sanity check:

    console.log((!undefined) === true); // true
    console.log((!!undefined) === false); // true
    console.log(undefined === false); // false
    

    This is a common usage of short circuiting. Because PrimaryColors is initially undefined (false), it will pass {} to the function.

    PrimaryColors || (PrimaryColors = {})