Search code examples
javascriptuglifyjs

Chaining several function definitions using the comma operator


I was taking a look at the source code of Uglify-js where I noticed something interesting. In bin/uglifyjs (ref) a couple of functions are defined like this:

//syntax A
var defsym = function(sym) {
  ...
},
defval = function(v) {
  ...
};

Considering that Uglify-js is written by professionals and is used in many products like JQuery, I don't understand why the code isn't written like this:

//syntax B
var defsym = function(sym) {
  ...
};
var defval = function(v) {
  ...
};

This will make it more clear that these are two local variables. Or how about this:

//syntax C
function defsym(sym) {
  ...
}
function defval(v) {
  ...
}

This one makes the defsym and defval functions be available through the entire scope of the mother function.

Why would they choose the first syntax? Why not the other syntaxes?


Solution

  • Why wouldn't they use Syntax B? Because it requires more characters.

    Why wouldn't they use Syntax C? Because its meaning is not entirely the same. Function declarations are not exactly the same as function expressions.


    Now I see that the assignments are taking place in a try/catch, which means that they are in a block.

    It's invalid to declare functions in a block (even though some implementations allow it).

     // Invalid
    try {
        function defsym(sym) {
            // ...
        }
        // ...
    } catch(e) {
        // ...
    }
    

     // Valid
    try {
        var defsym = function(sym) {
            // ... 
        },
        // ...
    } catch(e) {
        // ...
    }
    

    So this explains why they didn't choose Syntax C.

    Also, "strict mode" will absolutely prohibit such invalid declarations by throwing an error.