[Javascript] Anonymous functions in parameter space

liorean liorean at gmail.com
Thu Jul 21 02:47:58 CDT 2011


On 20 July 2011 19:03, Paul M Foster <paulf at quillandmouse.com> wrote:
> Hopefully, I'll get the terminology right here. If you, please correct
> me.
>
> Why is it common practice to write pass anonymouse functions as
> parameters to other functions in javascript? Example:
>
> function alfa(function(){ do_some_stuff; }){ do_other_stuff; };
>
> I see this a lot, and it's unbelievably confusing to decode/read. Why is
> it done this way? Instead, why not do it this way:
>
> function bravo() { do_some_stuff; };
>
> var charlie = bravo();

Don't see why you're doing this if you're trying to do a rewrite of
the example above, since that example contained no invocation of it.

> function alfa( parm ) { do_other_stuff; };
>
> alfa(bravo);
>
> Any help?

Well, while there's no real true answer to your question (because
reasons vary between developers), there's a few ones I can think of:

- Your rewrite induces namespace pollution. Many developers avoid
unnecessary variables, particularly global variables, as much as they
can.
- Due to lexical scoping and closure creation, not declaring functions
ahead of time but in the context they are needed can allow values to
be propagated through closures instead of being passed around as
variables.
- Anonymous functions have often been used to execute code that
requires variable use but where the developer doesn't want those
variables in the lexical environment it's contained in - for example
to keep variables private and not exposed to other functions in the
same lexical context. Now, let can do that instead of anonymous
functions...
- They are as close to lambda expressions as we can get.
- Using anonymous functions creates new function objects every time
the code is invoked, while referencing a function name reuses the same
function object.
- Maintaining style with libraries.
-- 
David "liorean" Andersson


More information about the Javascript mailing list