Reputation: 11140
I sometimes see JS constructs like this:
var foo = (function(){ return some_expression; })();
What can be the reason for this? Is this in any way different to the much simpler:
var foo = some_expression;
I happen to came across such an example here (the window.requestAnimFrame = ...
code) but I've seen it in many others places.
I know one reason to wrap stuff in a lambda function is to keep variables local, but that doesn't apply in this particular example.
Upvotes: 3
Views: 125
Reputation: 503
Not that there seems to be any difference in your case but before ECMAScript 5, undefined
was a property of the window
object and was writable, so undefined = "123"
would replace its value. This means that whenever any program below this line of code would try to check something like this-
var foo;
foo === undefined // false
one would get a wrong result.
In order to avoid this, a coding pattern like this was used -
(function(foo, bar, undefined) {
// your code here
// undefined here will always be the correct value (i.e., undefined === undefined) regardless of it being polluted somewhere outside this block
})(foo, bar)
But, this was pre ES5. So, it won't matter anymore
Upvotes: 1