Variable declaration Javascript, why is this legal?

advertisements

This question already has an answer here:

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

I just encountered this variable declaration syntax for the first time.

var myVar = (function() {
    return 1;
})();

My 2 main questions are..

What is it called, and why is it legal?

Forgive me if this question has been asked before, I tried searching around but I have no idea what this notation is called so I wasn't able to find anything.

Also, I should add, what is the function of the 2 sets of parentheses? The first of which encloses the function, the second of which is empty.


Self executing functions are typically used to encapsulate context and avoid name collusions. Any variable that you define inside the (function(){..})() are not global.

The following code:

var same_name = 1;

var myVar = (function() {
    var same_name = 2;
    console.log(same_name);
})();

console.log(same_name);

produces this output:

1
2

By using this syntax you avoid colliding with global variables declared elsewhere in you javascript code.