What Does (Function (X,Y){...})(A,B); Mean in JavaScript

What does (function (x,y){...})(a,b); mean in JavaScript?

In javascript you can have anonymous and self invoking functions.

function add(a, b)
{
return a + b;
}

is same as

var add = function (a, b) {
return a + b;
}

and you call these as

add(10, 20)

You can define the function and call it immediately as

(
function(a, b)
{
return a + b;
}
)(10, 20);

The

   (
function(a, b)
{
return a + b;
}
)

part defines a function, and the (10, 20) immediately after it calls the function just defined, with 10 and 20 as arguments to it.

Since the function does not have a name, it cannot be used later in the code.

The code in your question is probably minified, and creates a function in a similar way and calls it immediately.

could you explain the function in javascript?

On its own it does nothing except declare a variable that isn't used - it should invoke some other functions to do something useful.

That said, what you have is an immediately invoked function expression, i.e. an anonymous function:

function() { ... }

which is invoked with no parameters:

(f....)();

The rationale is two fold:

  • it allows the function to be defined and called without giving it a name in the global name space
  • any variables defined within the function are also held within that scope, and don't pollute the global name space.

JS function definition : meaning of the last parentheses

meaning of the last brakets

(function() {
....
})();

The () in the end causes the code inside the function to be executed immediately.

(function(param) {
....
})(JQuery);

The (JQuery) in the end causes the code inside the function to be executed immediately, passing JQuery as a parameter to it.

(function(chat, Friend) {
....
})(chat, chat.module("friend"));

The (chat, chat.module("friend")) in the end causes the code inside the function to be executed immediately, passing chat and chat.module("friend") as parameters to it.

A Javascript function

Your syntax is incorrect. Edit: fixed.

Look at a normal function definition that you want to call once and only once:

function add(x,y) {
var z = x + y;
// do something with z
}

add(2,3);

You could reduce this code so that you execute it straight away, there is no need to name it add:

(function(x ,y) {
var z = x + y;
// do something with z
})(2,3)

Note how we have surrounded the function with a set of parenthesis to make it a callable expression. This pattern is often used to create a closure (capture the state of) certain variables, for example:

jQuery.noConflict(); //Disables the use of $ in the global scope
(function($) {

//Safely use $ inside this function
$('.link').click(function(e) {
//etc
});

})(jQuery);

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

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)

why are javascript functions like this

Short answer: Those are immediately invoked functions that provide lexical scope and closures.

For a better explanation please take a look at this answer I posted some time ago.

UPDATE:

Lexical scope means that variables declared within a function won't be visible outside of the function body.

Closure is a way to keep references to variables that would otherwise be out of scope, because if they were in scope where the function body was defined then it is available to any subsequent invocation of that function. See: Closure on Wikipedia.

UPDATE 2:

If you really want to understand all of these then I strongly recommend watching the 1986 Structure and Interpretation of Computer Programs MIT lectures by Gerry Sussman and Hal Abelson
(available on YouTube). In my opinion there is no better way to truly understand JavaScript than watching those very lectures, even though they are not about JavaScript. You will quickly see which language was really the inspiration for Brendan Eich when he designed JavaScript. Hint: It was not Java.

javascript syntax explanation

What's happening is, an anonymous function expression is defined (in parentheses) -

(function([arg, arg ...]) {

//javascript code here

})

The function is then immediately called using the () at the end of the function, just as as you'd call a normal function var result = someFunction(). So , for example -

(function() {
alert('Called by "()" at end of function');
})()

You can also pass arguments to the anoymous function, via the parentheses -

(function(username) {
alert('Called by "()" at end of function. Hello ' + username + '!');
})('Dave')

var functionName = function() {} vs function functionName() {}

The difference is that functionOne is a function expression and so only defined when that line is reached, whereas functionTwo is a function declaration and is defined as soon as its surrounding function or script is executed (due to hoisting).

For example, a function expression:

// TypeError: functionOne is not a functionfunctionOne();
var functionOne = function() { console.log("Hello!");};

What is the (function() { } )() construct in JavaScript?

It’s an Immediately-Invoked Function Expression, or IIFE for short. It executes immediately after it’s created.

It has nothing to do with any event-handler for any events (such as document.onload).

Consider the part within the first pair of parentheses: (function(){})();....it is a regular function expression. Then look at the last pair (function(){})();, this is normally added to an expression to call a function; in this case, our prior expression.

This pattern is often used when trying to avoid polluting the global namespace, because all the variables used inside the IIFE (like in any other normal function) are not visible outside its scope.

This is why, maybe, you confused this construction with an event-handler for window.onload, because it’s often used as this:

(function(){
// all your code here
var foo = function() {};
window.onload = foo;
// ...
})();
// foo is unreachable here (it’s undefined)

Correction suggested by Guffa:

The function is executed right after it's created, not after it is parsed. The entire script block is parsed before any code in it is executed. Also, parsing code doesn't automatically mean that it's executed, if for example the IIFE is inside a function then it won't be executed until the function is called.

Update
Since this is a pretty popular topic, it's worth mentioning that IIFE's can also be written with ES6's arrow function (like Gajus has pointed out in a comment) :

((foo) => {
// do something with foo here foo
})('foo value')


Related Topics



Leave a reply



Submit