What is the meaning of this code (0, function) in javascript [duplicate]
I found this code in someone's code, it sound like this:
(0, function (arg) { ... })(this)
After I try to play around like below,
(0, function (arg) { console.log(arg) })(2);
console.log((0, 1, 2, 3));
(0, function plus1 (arg) { console.log(arg + 1) }, function plus2 (arg) { console.log(arg + 2) })(5);
I found that it will always return last item in the bracket.
I wonder what is the name of this programming pattern and what is the use case?
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
typical example could be,
for(var i=0,j=10; i < j; i++){
// code ...
}
comma operator would evaluate expressions from left-to-right and return result of right most expression
// e.g.
var a = 1, b= 2, c = 3, d = function(){ console.log("a => " + a) }()
It is a comma operator wrapped with a self-executing anonymous function. However, I have no idea as to why the meaningless 0
was included except for obfuscation purposes.