

Ask HN: JS, what is this called and how does it work? - uptownhr

(function(test){console.log(test)})(1)<p>I don&#x27;t think this really exists in other languages outside of JS. Where you can send in a parameter this way. I understand that the test variable becomes what ever you pass in the tail end but how does this work? What is this called so I can better ask other JS developers?
======
cabirum
Immediately Invoked Function Expressions (IIFE).

[http://benalman.com/news/2010/11/immediately-invoked-
functio...](http://benalman.com/news/2010/11/immediately-invoked-function-
expression/)

Not unique to js, e.g. upcoming php v7 will support these.

------
ayers
What you have is a self executing anonymous function. Now you know the name
you will be able to find out all the information you need. For example:
[http://esbueno.noahstokes.com/post/77292606977/self-
executin...](http://esbueno.noahstokes.com/post/77292606977/self-executing-
anonymous-functions-or-how-to-write)

~~~
uptownhr
thank you!

------
echeese
This is the same as:

    
    
        var func = (function(test){console.log(test)});
        func(1);
    

What's going on is you're creating an anonymous function, and then calling it.

------
uptownhr
So after looking at this longer, it makes a lot more sense. Basically, things
are evaluated left to right. The first (function(){}) evaluates the
function(){} and returns the function. Then the function is called with the
second (1), and passing that in as a param.

~~~
Stoo
That's it. This is often called the module pattern. It's often used to avoid
polluting the global scope with variables, e.g.

(function() { var x = 1; console.log(x); })();

console.log(x);

Would output:

1

undefined

