sigmaxf
sigmaxf

Reputation: 8492

Why is this javascript function inside parenthesis?

I was looking for a solution to a problem and I found this aswer https://stackoverflow.com/a/6962808/2724978

The function written is:

(function loop() {
    var rand = Math.round(Math.random() * (3000 - 500)) + 500;
    setTimeout(function() {
            doSomething();
            loop();  
    }, rand);
}());

My question is, why is the function insite parenthesis an also having () at the end? It got me a bit confused, never seen this before.

Upvotes: 1

Views: 94

Answers (2)

RemcoGerlich
RemcoGerlich

Reputation: 31270

The snippet creates an anonymous function, and immediately calls it.

The problem with doing without parens,

// This is a syntax error
function () {
  something;
}();

is that that is a syntax error; because the statement starts with 'function', the parser expects a function name to follow. Wrapping it all in parens makes it syntatically legal to define an anonymous function there.

// This is valid syntax
(function () {
  something;
}());

Upvotes: 1

duncanhall
duncanhall

Reputation: 11431

This is an example of an Immediately Invoked Function Expression.

The link above will explain all you need to know, but essentially there are two things happening.

  • Wrapping within parenthesis tells the parser to treat everything within them as an expression.
  • Calling the expression (with ()) immediately afterwards ensures the scope of that expression is sealed.

Upvotes: 3

Related Questions