Judson Terrell
Judson Terrell

Reputation: 4306

How to pass argument to javascript anonymous function

Can someone explain to me why x is undefined? Shouldn't be 123?

doSomething = (function(x) {
   alert(x)
})();

doSomething(123);

Upvotes: 0

Views: 87

Answers (3)

Judson Terrell
Judson Terrell

Reputation: 4306

Wouldn't this be the better way? let it init, then call it passing an argument?

doSomething = (function(x) {

    return(
            init = function(x){   

             alert(x)
            }
        )


})();

doSomething("test")

Upvotes: 0

Michael Chaney
Michael Chaney

Reputation: 3031

You need to remove the parens, right now you define the function and immediately call it with an empty argument list. Change it to this:

doSomething = function(x) {
   alert(x)
}

And then you can call it.

Upvotes: 2

gen_Eric
gen_Eric

Reputation: 227260

doSomething isn't a function. It's undefined.

doSomething = (function(x) {
   alert(x)
})();

This declares an anonymous function, immediately executes it (that's what the () does), then sets doSomething to the return value - undefined. Your anonymous function takes one parameter (x), but nothing is passed to it, so x is undefined.

You probably want this:

doSomething = function(x) {
   alert(x)
};

doSomething(123);

Upvotes: 4

Related Questions