Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this "(function(){});", a function inside brackets, mean in javascript? [duplicate]

Possible Duplicates:
What does this mean? (function (x,y)){…}){a,b); in JavaScript
What do parentheses surrounding a JavaScript object/function/class declaration mean?

Hi All

I don't know what the following does:

(function(){   // Do something here   ... })(someWord) //Why is this here?; 

My questions are:

  1. What's the meaning of putting a function inside brackets .i.e. (function(){});?
  2. What do the set of brackets do at the end of a function?

I usually see these in jquery codes, and some other javascript libraries.

like image 806
Shaoz Avatar asked Oct 28 '10 14:10

Shaoz


People also ask

What does function with brackets mean?

Braces or curly brackets { } are used when the domain or range consists of discrete numbers and not an interval of values. If the domain or range of a function is all numbers, the notation includes negative and positive infinity . If the domain is all positive numbers plus 0, the domain would be written as .

What are the brackets in functions for JavaScript?

In JavaScript, the functions wrapped with parenthesis are called “Immediately Invoked Function Expressions" or "Self Executing Functions. The purpose of wrapping is to namespace and control the visibility of member functions. It wraps code inside a function scope and decrease clashing with other libraries.

What is inside the bracket of a function?

Parentheses, ( or ), are used to signify that an endpoint value is not included, called exclusive. Brackets, [ or ], are used to indicate that an endpoint value is included, called inclusive.

What is double parentheses in JavaScript?

It means that the first function ( $filter ) returns another function and then that returned function is called immediately. For Example: function add(x){ return function(y){ return x + y; }; } var addTwo = add(2); addTwo(4) === 6; // true add(3)(4) === 7; // true. Follow this answer to receive notifications.


2 Answers

You're immediately calling an anonymus function with a specific parameter.

An example:

(function(name){   alert(name); })('peter') 

This alerts "peter".

In the case of jQuery you might pass jQuery as a parameter and use $ in your function. So you can still use jQuery in noConflict-mode but use the handy $:

jQuery.noConflict() (function($){   var obj = $('<div/>', { id: 'someId' }); })(jQuery) 
like image 92
pex Avatar answered Sep 19 '22 17:09

pex


You are making a function that is immediately being called, with someWord as a parameter.

like image 20
Rocket Hazmat Avatar answered Sep 21 '22 17:09

Rocket Hazmat