I was looking at the output of some stuff from UglifyJS and happened across some code like the following:
var a = 0;
var b = function () {
return function () {
a++;
}(), 'Hello, World'
}();
After running that code a
is 1
and b
is the string Hello, World!
.
At first glance it appears that b
will be undefined
since it looks like the result of a function with no return value is being returned, but that is followed by a comma and a string literal.
Why does this work?
And why doesn't UglifyJS just execute the anonymous function and then return Hello, World!
as the next statement?
It works due to the comma operator. From the MDN specs:
The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand.
Both functions are IFFYs, they are inmediately executed.