What does the below JavaScript mean? Why is the function embedded inside ()?
(function() {
var b = 3;
a += b;
}) ();
Justin's answer explains it pretty well, but I thought I'd just add that the first set of parentheses (the opening one before function) is actually completely unnecessary as far as program execution is concerned. For readability, however, it's very important! When I see this:
(function() {
I know that this function is being called immediately, without having to scroll down to find the end of the block. This is important because sometimes you want to assign the return value of the function to a variable, and sometimes you want to assign the function to a variable. See:
var x = (function() {
return 4;
})();
var y = function() {
return 4;
};
// typeof x == integer (4)
// typeof y == function