Finwood
Finwood

Reputation: 3991

What does (foo) in function(args){ ... }(foo) mean?

I've been struggling with Javascript objects.

What does (foo) in function(args){ ... }(foo) mean?

Upvotes: 3

Views: 660

Answers (5)

TecHunter
TecHunter

Reputation: 6131

You are declaring a function then right after that you call it. you could do it in 2 steps :

function f(args){}

f(foo);

Single step and anonymous :

(function(args){})(foo);

Upvotes: 3

metadings
metadings

Reputation: 3848

When you see a function (args) { } followed by brackets (foo), it is an immediately invoked function expression (IIFE - pronounced 'iffy').

function (args) { } (foo);

is basically the same as

var foofun = function (args) { };
foofun(foo);

or

function foofun(args) { }
foofun(foo);

the expression is just also anonymous, because the function isn't stored into a var and has no name.
So the foo is just the parameter for the args argument.

Upvotes: 2

basilikum
basilikum

Reputation: 10526

Your statement can be rewritten to:

function xy(args) {
   //code here
}

xy(foo);

So basically you are just directly calling the function after it's definition and passing a variable foo as argument.

Upvotes: 0

Andrei Madalin Butnaru
Andrei Madalin Butnaru

Reputation: 4104

the function is anonymous (does not have a name), and you call that function with the argument foo

Upvotes: 1

Dennis
Dennis

Reputation: 14465

this is an example for an immediately invoced function expression (IIFE). After your anonymous function is declared, it is immediately invoced by calling it with the parameter foo.

foo is probably just an example for any object that you may pass as a parameter to your function declaration which is about to be called right away.

Upvotes: 1

Related Questions