2

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.

yellowhat5
  • 129
  • 1
  • 1
  • 6
  • 2
    You're setting `myVar` to whatever is returned by an Immediately Invoked Function Expression or IIFE: http://en.wikipedia.org/wiki/Immediately-invoked_function_expression; They're quite useful, but in the given example it's the same as `myVal = 1`. See this simple fiddle example: http://jsfiddle.net/ChaseWest/2w69Z/ – Chase May 18 '14 at 05:08
  • That programming pattern is called a Closure. It's legal because variables in javascript can be functions and those functions can even be self-executing (as in your example--that's what the empty parentheses at the end do for you.) Closures are very useful programming constructs and are well worth a Google search. Check them out! – markE May 18 '14 at 05:13

3 Answers3

1

I am not sure what this is called, other than defining an anonymous function and immediately invoking it.

It is perfectly legal, because

  1. Defining an anonymous function is legal.
  2. Invoking it and assigning the return value is also legal.

The end result is that myVar = 1.

merlin2011
  • 71,677
  • 44
  • 195
  • 329
1

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.

Daniel
  • 1,531
  • 13
  • 16
0

This is an anonymous function (also called lambda function) that is being executed immediately with its return value (1) being assigned to a variable (myVar). It's legal because the specification says it is. It is a very common feature in many languages.

Brad
  • 159,648
  • 54
  • 349
  • 530