Reputation: 57212
What is the difference between the following two blocks?
// block 1
{
console.log("anonymous block");
}
// block 2
(function anon() {
console.log("anonymous block 2");
})();
I ran this in Netbeans (using the node.js plugin) and they both seem to work...
Upvotes: 3
Views: 2014
Reputation: 46233
The difference is that you can use the latter form to hide global variables without destroying them.
For example, suppose you're using the jQuery library, which by default aliases its main namespace to $
. If you wanted to use $
for a different purpose without changing how $
is normally used, you could do something like this:
(function($) {
// Use $ without clashing with the jQuery object.
})(someObject);
In fact, it's also useful for one other purpose. Since undefined
is NOT a reserved word in JavaScript, it can be given a value and lose its purpose. So you could simply not pass a value into an undefined
parameter, and you know it will behave properly without clashing with a global value.
undefined = "some not-undefined value"; // you'd have to be an idiot to do this but I've seen it done
(function(a, b, undefined) {
console.log(typeof(undefined) === "undefined"); // true
})(someA, someB);
Upvotes: 6
Reputation: 66394
block 1
will have scope of the block it is inside, setting a var will overwrite it in the parent, you can use let
.
var a = 2;
{
var a = 4;
}
a; // === 4
block 2
will have global scope but anything set by var
will be forgotten after it is executed.
var a = 2;
(function(){
var a = 4;
})();
a; // === 2
Upvotes: 0
Reputation: 96845
The first creates a block, which is not the same as a function. You can use anonymous self-executing functions to create local, private variables and return an interface from it. It's called the Module Pattern.
var Module = (function() {
var method = function() { console.log("anonymous block"); },
someOtherMethod = function() {};
return { // return our interface as an object literal
method: method,
someOtherMethod: someOtherMethod
};
})();
Module.method(); // "anonymous block"
We can call it, keeping the variables method
and someOtherMethod
isolated from the global scope. It's one of the most important, useful features of object-oriented programming in JS.
Upvotes: 3