1

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.

Community
  • 1
  • 1
sigmaxf
  • 7,998
  • 15
  • 65
  • 125
  • because the function is not being evaluated. – Nina Scholz Mar 04 '16 at 12:02
  • The 2 parenthesis at the end is to call the loop function. The block is between in parenthesis is a special notation to make everything inside private (not accesible from outside). – Walfrat Mar 04 '16 at 12:05
  • If you type `function loop() { ... };` then that **defines** the function. It is not *executed* yet. Invoking the function is done by `()` (which is argument list) and that actually executes the function. You place a name before `()` and you get `loop()` which tells the JS engine to execute the function. – Mjh Mar 04 '16 at 12:06
  • @Walfrat: the parens do nothing to make what's inside any more or less private. – RemcoGerlich Mar 04 '16 at 12:08
  • It is called immediately-invoked function expression. The code will executed immediately but has its own private scope. – d-bro82 Mar 04 '16 at 12:08
  • 2
    Possible duplicate of [JavaScript IIFE](http://stackoverflow.com/questions/21781551/javascript-iife) – Evan Trimboli Mar 04 '16 at 12:08
  • @RemcoGerlich Yes i know i was more telling about the whole block with the parenthesis and the function call. – Walfrat Mar 04 '16 at 12:10

2 Answers2

3

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.
duncanhall
  • 11,035
  • 5
  • 54
  • 86
1

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;
}());
RemcoGerlich
  • 30,470
  • 6
  • 61
  • 79