Ickhyun Kwon
Ickhyun Kwon

Reputation: 1703

What does this javascript code mean?

var myval = (function(){})();

I don't understand (function..) meaning and even else code.

Upvotes: 2

Views: 371

Answers (6)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340973

This function(){} defines anonymous function (closure) with no body. By wrapping it in braces and adding empty parameters list at the end (()) you are running this closure. This is essentially equivalent to:

var f = function() {};
f();

Would this be easier to grasp?

(function(x, y, z){})(1, 2, 3)

Upvotes: 1

jAndy
jAndy

Reputation: 236162

What you've got there is a:

self-invoking anonymous function

You're first creating a function-expression by having paranthesis around the function itself. Just to write

function() {
}()

would not work in this instance, because this would define a function-declaration.

So after we have that, we can call itself by appending ()

(function() {
})();

To verify that, try this:

var myval = (function(){return 'self executed!'})();

alert(myval); // === 'self executed'

Upvotes: 8

nico
nico

Reputation: 51680

Let's analyze it piece by piece:

This define an anonymous function (i.e. a function with no name)

function(){}

Of course it would be more useful to put some instruction in between the {} brackets.

Now if you did

myval = function(){<something>};

You assign the function to myval (the function, NOT its return value!)

So then you could call myval() and it would be the same as calling the function itself.

Here instead you do call the function by putting () at the end. Therefore:

var myval = (function(){})();

calls the function, and puts the result (not the function itself this time) in myval

Upvotes: 0

chx
chx

Reputation: 11790

This creates an anonymous function and immediately calls it. For example

(function ($) {
  // Original JavaScript code.
})(jQuery);

will allow you to use $ in there and it equals jQuery.

Upvotes: 2

Quentin
Quentin

Reputation: 944443

  • function(){} — is a function expression, it defines a function
  • (function(){}) — wrapping it like this makes sure it gets treated as an expression
  • (function(){})() — Adding () calls the function

And then the return value is assigned to a variable.

This is usually used to allow variables to be used without polluting the global scope.

Upvotes: 7

Related Questions