In this particular case it seems superfluous, but sometimes this approach is useful.
For example, with eval
:
(function() {
(0,eval)("var foo = 123"); // indirect call to eval, creates global variable
})();
console.log(foo); // 123
(function() {
eval("var bar = 123"); // direct call to eval, creates local variable
})();
console.log(bar); // ReferenceError
It's also useful when you want to call a method without passing the object as the this
value:
var obj = {
method: function() { return this; }
};
console.log(obj.method() === obj); // true
console.log((0,obj.method)() === obj); // false
Also note that, depending on the context, it might be the arguments separator instead of a comma operator:
console.log(
function(a, b) {
return function() { return a; };
}
(0, function (arg) { /* ... */ })(this)
); // 0
In this scenario, (0, function (arg) { /* ... */ })
are the arguments (a=0, b=function (arg) { /* ... */ }
) to the function
function(a, b) {
return function() { return a; };
}
rather than the comma operator. (Then, the (this)
at the end is function call with argument this
to the returned function function() { return a; }
. But this part is not relevant to the comma operator/argument separator difference)