2
function animator(shapes, $timeout) {
    (function tick() {
        var i;
        var now = new Date().getTime();
        var maxX      = 600;
        var maxY      = 600;
        var now = new Date().getTime();

        $timeout(tick, 30);
    })(); // What is this for?
}

Here I don't understand the functionality. I am new to this kind of script. Inside of the main function is like ()(). What is this for?

Nabil Kadimi
  • 10,078
  • 2
  • 51
  • 58
Hacker
  • 7,798
  • 19
  • 84
  • 154
  • I think it's called a self invoking function...A function that is defined and immediately executed. – Lix Aug 13 '15 at 11:57
  • 6
    Possible duplicate: [iife - What is the (function () {})() construct in javascript?](http://stackoverflow.com/q/8228281/1168892) – Dominik Schreiber Aug 13 '15 at 11:58

4 Answers4

7

This is an IIFE, Immediately-invoked function expression.

Why use an IIFE?

Why?: An IIFE removes variables from the global scope. This helps prevent variables and function declarations from living longer than expected in the global scope, which also helps avoid variable collisions.

Why?: When your code is minified and bundled into a single file for deployment to a production server, you could have collisions of variables and many global variables. An IIFE protects you against both of these by providing variable scope for each file.

Nabil Kadimi
  • 10,078
  • 2
  • 51
  • 58
3

I don't know if it has a separate name, it's just immediately executed.

Instead of function a(){..}; a() you can do (function(){..})()

Useful for scoping the vars inside, while placing/executing it right where you want it, also you don't have to invent a name for it.

Rodia
  • 1,407
  • 8
  • 22
  • 29
birdspider
  • 3,034
  • 1
  • 16
  • 25
2

(function(){console.log('test')})() will call function immediately. So if you will write this statement then it will be called immediately and prints test on console.

Juned Lanja
  • 1,466
  • 10
  • 21
1

This is a self-invoking function as @lix pointed out.

Function expressions can be made "self-invoking".

A self-invoking expression is invoked (started) automatically, without being called.

Function expressions will execute automatically if the expression is followed by ().

Community
  • 1
  • 1
Shambhavi
  • 305
  • 1
  • 14