Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript function vs. ( function() { ... } ());

Tags:

javascript

I have often see expressions such as:

(function () {
    var x = 1;
    ...
}());

How do I interpret it? syntactically, this alone is a anonymous function definition.

function() {
...
}

what the () after that? and why put it in the enclosing ()?

Thanks

like image 258
Oliver Avatar asked Jan 26 '11 15:01

Oliver


People also ask

What is the difference between function and function ()?

function is a language keyword used to define functions. Function is the builtin prototype object that represents all functions. Save this answer.

What is function () in JS?

A function in JavaScript is similar to a procedure—a set of statements that performs a task or calculates a value, but for a procedure to qualify as a function, it should take some input and return an output where there is some obvious relationship between the input and the output.

What are the 3 types of functions in JavaScript?

There are 3 ways of writing a function in JavaScript: Function Declaration. Function Expression. Arrow Function.

What is difference between function and function expression in JavaScript?

The main difference between a function expression and a function declaration is the function name, which can be omitted in function expressions to create anonymous functions. A function expression can be used as an IIFE (Immediately Invoked Function Expression) which runs as soon as it is defined.


1 Answers

Exactly the same, except that it is being invoked immediately after being converted into a function expression.

// v-----first set of parentheses makes the function an expression
   (function () {
       var x = 1;
       ...
   }());
//  ^-----this set is used to invoke the function

Same as if you did:

   var myfunc = function () {
       var x = 1;
       ...
   };
   myfunc();

or (similar) this:

   var returnValue = function () {
       var x = 1;
       ...
   }();

Get rid of the names, move the parentheses around, and you can see they're not that different.

like image 159
user113716 Avatar answered Nov 02 '22 23:11

user113716