0

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

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

doSomething(123);
1
  • 1
    This is called IIFE. Commented Oct 27, 2014 at 21:45

3 Answers 3

4

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);
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

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")

11 Comments

Now you're just making it more complicated. Why are you making a global variable init? Why does the main anonymous take a parameter x? If you really wanted to do it this way, do this: doSomething = (function(){ return function(x){ alert(x); }; })();
What problem are you actually trying to solve here? Why do you need to use an anonymous function that is auto-invoked? Why not just doSomething = function(x){ alert(x); };?
one of my younger coworker developers has been wrapping all of his functions this way and i am trying to wrap my head around why. i never code this way but he insisted it was good practice? any explanation?
It's good practice if your functions are accessing variables outside their scope. Like, if you are creating variables that your functions need, that aren't passed in. This keeps them contained and out of the global scope. P.S. make sure to use var before your local vars!
Thanks for your help. if you could post an example of your last comment ("Like, if you are creating variables that your functions need, that aren't passed in. This keeps them contained and out of the global scope"), that would be great.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.