Nik So
Nik So

Reputation: 16811

small question on js syntax

I saw this syntax many times but I couldn't find a way to google it properly, I hope I can get some help here:

  <script>
    (function(){
      //code goes here
    })();
  </script>

Why is the function keyword wrapped in the parenthesis? What does it do and what is this called?

Upvotes: 1

Views: 82

Answers (4)

Tomalak
Tomalak

Reputation: 338188

It is called an anonymous function that is being called immediately.

// defining and calling a named function
function x() { /* do something */ }
x();

// defining an anonymous function (usually to assign it to a variable)
var x = function () { /* do something */ };
x();

// defining and calling an anonymous function in one step 
(function () { /* do something */ })();

Most often the last pattern is used as part of creating a closure.

Upvotes: 5

vol7ron
vol7ron

Reputation: 42099

You can google (or search on Stack Overflow) JavaScript anonymous function or closure

Some links:

Upvotes: 2

thejh
thejh

Reputation: 45568

See Bob Fincheimers answer for an explaination of what it means.

It is used to wrap a bunch of functions and variables that the programmer doesn't want to be visible from the outside - that's good when you're using libraries or so, you don't want them to block many function names for internal stuff.

Upvotes: 1

Bob Fincheimer
Bob Fincheimer

Reputation: 18056

In js, the syntax:

function() { //code }

defines an anonymous function. You can store this into a variable and call it:

var a = function() { //code };
a();

or if you don't want to bother assigning it you can do it in one step.

(function() { //code })();

the parenthesis are necessary because:

function() { //code }();

is not proper syntax.

This syntax is useful in certain situations to help memory management as well as change variable names. For example in javascript you have a jQuery object, but most people refer to it as $. But sometimes $ is used as some other variable instead of the jQuery object. To fix this, you can wrap your code in:

(function($) { // code that uses $ })(jQuery);

That way you can use the dollar sign and not have to worry whether or not it actually points to the jQuery object or not.

Upvotes: 5

Related Questions