Advanced JavaScript: Why Is This Function Wrapped in Parentheses

Advanced JavaScript: Why is this function wrapped in parentheses?

There are a few things going on here. First is the immediately invoked function expression (IIFE) pattern:

(function() {
// Some code
})();

This provides a way to execute some JavaScript code in its own scope. It's usually used so that any variables created within the function won't affect the global scope. You could use this instead:

function foo() {
// Some code
}
foo();

But this requires giving a name to the function, which is not always necessary. Using a named function also means at some future point the function could be called again which might not be desirable. By using an anonymous function in this manner you ensure it's only executed once.

This syntax is invalid:

function() {
// Some code
}();

Because you have to wrap the function in parentheses in order to make it parse as an expression. More information is here: http://benalman.com/news/2010/11/immediately-invoked-function-expression/

So to recap quickly on the IIFE pattern:

(function() {
// Some code
})();

Allows 'some code' to be executed immediately, as if it was just written inline, but also within its own scope so as not to affect the global namespace (and thus potentially interfere with or be interfered with by, other scripts).

You can pass arguments to your function just as you would a normal function, for example,

(function(x) {
// Some code
})(1);

So we're passing the value '1' as the first argument to the function, which receives it as a locally scoped variable, named x.

Secondly, you have the guts of the function code itself:

delete x;
return x;

The delete operator will remove properties from objects. It doesn't delete variables. So;

var foo = {'bar':4, 'baz':5};
delete foo.bar;
console.log(foo);

Results in this being logged:

{'baz':5}

Whereas,

var foo = 4;
delete foo;
console.log(foo);

will log the value 4, because foo is a variable not a property and so it can't be deleted.

Many people assume that delete can delete variables, because of the way autoglobals work. If you assign to a variable without declaring it first, it will not actually become a variable, but a property on the global object:

bar = 4; // Note the lack of 'var'. Bad practice! Don't ever do this!
delete bar;
console.log(bar); // Error - bar is not defined.

This time the delete works, because you're not deleting a variable, but a property on the global object. In effect, the previous snippet is equivalent to this:

window.bar = 4;
delete window.bar;
console.log(window.bar);

And now you can see how it's analogous to the foo object example and not the foo variable example.

Why are parenthesis used to wrap a javascript function call?

This is done for readability.

There isn't a real functional difference between the two examples you've given, but both of them are very close to a simple function declaration, which is different. The parenthesis are added for readability, in order to distinguish them.

Here is what each of your snippets do:

In the first of your two snippets, the first parenthesis will be evaluated as the value of the enclosed function. Then this value will be called as a function. So ultimately the function will be executed, which is probably what you care about.

In your second snippet, the outer parenthesis will be evaluated as containing a function which is declared inline and immediately executed. Again, the function will be executed, which is still probably what you care about.

Both of these will execute the same function, so there won't be any significant difference.

The difference between a snippet like yours and a simple function declaration:

The functions you've given are also identical to the following. I've just added a function name and assigned the return value for syntactical accuracy, which you can ignore for now.

// javascript...
var val =
function myFooFunc () {
alert("foo");
}();

However, this would be easily mistaken for a simple function declaration, which is different:

// javascript...
function myFooFunc () {
alert("foo");
}

Notice that the only real difference here is that this last function declaration is not executed immediately. The others are. So that is a very different behavior (the simple declaration may be executed later if it is called by name, or it may not ever execute at all). It's often hard to see that difference in the syntax right away, however, especially if the function body grows to be very long and requires scrolling on the screen.

Why are functions executed immediately?

When a function is immediately executed after it is declared, the value is often being returned to something (it may be part of an assignment statement). Sometimes the function is being executed right away because it contains inner functions and is being used to provide functional scope to the inclosed statements.

Essentially, people wrap parenthesis around the "executed immediately" form (both of your snippets, and the first one of my two) in order to give a visual cue to other developers that the function is being called immediately. It's just easier to read, since you might not catch the parenthesis until you got to the end of the function (or notice them at all).

Why are parentheses required around JavaScript IIFE?

The version of IIFE that is wrapped in parenthesis works, because this marks the declaration of the internal function declaration as an expression.

http://benalman.com/news/2010/11/immediately-invoked-function-expression/

For more detailed explanation please see:

Advanced JavaScript: Why is this function wrapped in parentheses?

HINT:

The invocation operator (()) only works with expressions, not declarations.

Why are there brackets outside of the curly brackets in this function and what does this mean?

The parenthesis are there to make the function return the object without having to wrap the entire object in braces with a return.

For example this doesn't work:

var PersonType = new GraphQLObjectType({
name: 'Person',
fields: () => { // interpreted as a block not an object
name: { type: GraphQLString },
bestFriend: { type: PersonType },
}
});

because the {} would be interpreted as a block, when you want to return an object.

You could do this:

var PersonType = new GraphQLObjectType({
name: 'Person',
fields: () => {
return { name: { type: GraphQLString },
bestFriend: { type: PersonType },
}
}
});

but that doesn't seem as nice as just using the parenthesis which will cause the function to return the object.

When do I include parenthesis when passing state into setState?

It's not really a react thing, it's a javascript syntax. Using parenthesis is a shortcut for returning an object.

For example,

const items = [1, 2, 3, 4, 5]

const withParenthesis = items.map((item) => ({item}));

// is the same with
const withoutParenthesis = items.map((item) => {
return {item};
})

Keep in mind that you need to manually return when not using ({})

Declaration function inside ( )

In your example, I see no reason for the parentheses.

For immediately invoked functions, Douglas Crockford recommends and provides a code sample as below. Source is http://javascript.crockford.com/code.html

When a function is to be invoked immediately, the entire invocation
expression should be wrapped in parens so that it is clear that the
value being produced is the result of the function and not the
function itself.

var collection = (function () {
var keys = [], values = [];

return {
get: function (key) {
var at = keys.indexOf(key);
if (at >= 0) {
return values[at];
}
},
set: function (key, value) {
var at = keys.indexOf(key);
if (at < 0) {
at = keys.length;
}
keys[at] = key;
values[at] = value;
},
remove: function (key) {
var at = keys.indexOf(key);
if (at >= 0) {
keys.splice(at, 1);
values.splice(at, 1);
}
}
};
}());

Coffeescript parentheses for function invocation

define (require) ->
return 'goodbye'

would be equivalent to the JavaScript code

define(function(require) { return 'goodbye' })

That is, a function call to define with a function as its first (and only) argument. It is probably not what you expected the snippet to do when you asked your question.

Something I found very helpful when I played around with CoffeeScript was to try things out in the on-line "try CoffeeScript" dialogue on the CoffeeScript website. This allows you to see the JavaScript that a given snippet is compiled to, and immediately see what effect e.g. adding parentheses or changing indentation has on the resulting JavaScript code. I definitely recommend doing that. :-)

Edit to reflect the edit in the question:

Yes, adding parentheses around the function ((require) -> return 'goodbye') is valid, and doesn't alter the behaviour. Note however that "foo (bar)" and "foo(bar)" is parsed differently by the parser; in the former the parenthes denote precedence (priority, "regular parentheses"), and in the latter they are function invocation parentheses.

"foo bar", "foo(bar)", "foo (bar)" all do the same thing, but whereas "foo bar, baz" and "foo(bar, baz)" work fine, "foo (bar, baz)" is a syntax error.

JavaScript plus sign in front of function expression

It forces the parser to treat the part following the + as an expression. This is usually used for functions that are invoked immediately, e.g.:

+function() { console.log("Foo!"); }();

Without the + there, if the parser is in a state where it's expecting a statement (which can be an expression or several non-expression statements), the word function looks like the beginning of a function declaration rather than a function expression and so the () following it (the ones at the end of the line above) would be a syntax error (as would the absense of a name, in that example). With the +, it makes it a function expression, which means the name is optional and which results in a reference to the function, which can be invoked, so the parentheses are valid.

+ is just one of the options. It can also be -, !, ~, or just about any other unary operator. Alternately, you can use parentheses (this is more common, but neither more nor less correct syntactically):

(function() { console.log("Foo!"); })();
// or
(function() { console.log("Foo!"); }());

What is the point of using a function expression over a function statement in Javascript?

Function expressions are useful in several circumstances:

When assigning a function to a property:

SomeClass.prototype.myMethod = function(args) {
// implementation
}

When creating a variable that may contain a different implementation based on circumstances:

var sortFn;

if (high > low) {
sortFn = function(...) {
// sort increasing order
}
} else {
sortFn = function(...) {
// sort decreasing order
}
}

// some code that uses sortFn()

In an IIFE (immediately invoked function expression):

var getUniqueID = (function() {
var counter = 0;
return function() {
return counter++;
}
})();

console.log(getUniqueID()); // 0
console.log(getUniqueID()); // 1
console.log(getUniqueID()); // 2

There are many other references on the usefulness of an IIFE:

Javascript why wrap a variable or constructor in an IIFE?

What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?

What is the (function() { } )() construct in JavaScript?

What is the purpose of a self executing function in javascript?

Advanced Javascript: Why is this function wrapped in parentheses?

Inline function expressions for passing a function as an argument:

fetch(someURL).then(function(value) {
// this is inside a function expression
}).catch(function(err) {
// handle errors here
});

myArray.forEach(function(item, index) {
// process each item of the array here
// in this function expression
});

What is the (function() { } )() construct in JavaScript?

It’s an Immediately-Invoked Function Expression, or IIFE for short. It executes immediately after it’s created.

It has nothing to do with any event-handler for any events (such as document.onload).

Consider the part within the first pair of parentheses: (function(){})();....it is a regular function expression. Then look at the last pair (function(){})();, this is normally added to an expression to call a function; in this case, our prior expression.

This pattern is often used when trying to avoid polluting the global namespace, because all the variables used inside the IIFE (like in any other normal function) are not visible outside its scope.

This is why, maybe, you confused this construction with an event-handler for window.onload, because it’s often used as this:

(function(){
// all your code here
var foo = function() {};
window.onload = foo;
// ...
})();
// foo is unreachable here (it’s undefined)

Correction suggested by Guffa:

The function is executed right after it's created, not after it is parsed. The entire script block is parsed before any code in it is executed. Also, parsing code doesn't automatically mean that it's executed, if for example the IIFE is inside a function then it won't be executed until the function is called.

Update
Since this is a pretty popular topic, it's worth mentioning that IIFE's can also be written with ES6's arrow function (like Gajus has pointed out in a comment) :

((foo) => {
// do something with foo here foo
})('foo value')


Related Topics



Leave a reply



Submit