[Javascript] defining functions before they're called

Mike Dougherty msd005 at gmail.com
Fri Aug 21 10:10:13 CDT 2009


On Thu, Aug 20, 2009 at 7:03 PM, Paul Novitski<paul at juniperwebcraft.com> wrote:
> Can you recall where you learned that calling before declaring a
> function was bad form? I'd love to trace that back to see where it
> comes from and whether it ever pertained to JavaScript.

I think I understand what you saying about a technical detail, however
I think there is another consideration...

Maintenance of a project/program is easier if declarations are easy to
find.  I'm not saying they must be first, but they probably should be
obvious and consistent.  Declaration first is one style of managing
that.  VB's "option explicit" prevents on-the-fly assignment of new
variables when a coder mistypes a name, so variables must be declared
before use in that case.  Rather than having declarations strewn
through code, they usually are put at the top/start of a procedure so
they can be easily found by the debugging/maintenance programmer.
Perhaps this convention is so ingrained that it became a general
unquestioned rule?

The fact that browsers seem to first read all the javascript in a page
to find function declarations doesn't mean you are calling a function
before it is defined - the browser implementation is doing a
pre-emptive step of looking for functions before running the code.
Function declaration anywhere in code is a special case of environment
setup.  It's not fair to say you can call code by name before it's
been named;  ex: we can't call closures before creating them:

var a = 1;
var result = myfunction( 2 ); // this can't work since myfunction
doesn't exist yet
var myfunction = function(p){ return a + p };

Sorry for so much (wandering) narrative - my point was (more
succinctly) that function declaration first is one style to keep code
organized and easier to find.  As long as everyone on a project
understands the convention, any style that works should be fine.



More information about the Javascript mailing list