Reputation: 312
I'm learning javascript from Crockford's book Javascript: The Good Parts. He explains there how to use closure to encapsulate information. E.g.
var myObject = (function () {
var value = 0;
return {
getValue: function () {
return value;
}
};
}());
If I have understood this correctly, the idea is that we define a function returning an object literal. This function is then invoked to initialize myObject. But what is the point of the outmost brackets?[(f...);]. Isnt the pair () enough to invoke the function we have defined?
Upvotes: 3
Views: 77
Reputation: 10614
You are correct; the outermost parentheses do nothing, although it is common practice to put them anyway -- it helps with readability. When people see a function enclosed in parentheses like that, they expect it to be immediately invoked, whereas if the parentheses were not there it may not be as apparent at first. It's nothing more than a visual cue here.
However, note that parentheses around a function are needed in some cases to make it a function expression rather than a function declaration.
For example, the following will not work:
function() {
// Do something...
}();
// Throws a syntax error.
In this case, you'll get a syntax error because the parser is expecting a function declaration, and you didn't give this function a name. In addition, you can't immediately invoke a function declaration. You need parentheses to convert this into a function expression:
(function() {
// Do something...
})();
The difference in a function declaration and a function expression is a function declaration can be used to declare a function in the same way as var
can be used to declare a variable:
// Declare the variable foo.
var foo;
// Declare the function bar.
function bar() {
// Do something...
}
A function expression, however, doesn't declare a variable. Rather it just creates a function which you can use for something, such as assign it to a variable or just to invoke.
In order to make a function expression you just have to start the line with something other than function
. A common technique, as seen above, is to start it with a parenthesis. As you mentioned you can also start the line with var something = ...
:
var foo = function() {
return 5;
}();
// foo is now 5
You can really start it with anything which would make a valid expression though:
!function() {
console.log(1);
}();
// logs 1
~function() {
console.log(2);
}();
// logs 2
+function() {
console.log(3);
}();
// logs 3
[ function() {
console.log(4);
}() ];
// logs 4
'Hello, World' == function() {
console.log(5);
}();
// logs 5
Of course, if you're trying to store the result of the function in a variable, you won't be able to use any of these patterns, as they all mess with the return value. Most people stick to wrapping functions in parentheses, whether they are necessary or not, just for the sake of consistency and readability.
Upvotes: 6