In JavaScript there are two main ways to declare a function, namely by declaration and by expression. For the majority of uses there is little difference, but there is a little sneaky-ness you should be aware of.
Function Declaration
To start off we’ll show an example of a function declaration (yes I’m using node-js … again!).
var sys = require('sys');
function helloWorld() {
sys.puts('Hello World!');
}
helloWorld();
As you’d expect you run the example and get the following :
Hello World!
Function Expression
So the same as a function expression is …
var sys = require('sys');
var helloWorld = function() {
sys.puts('Hello World!');
}
helloWorld();
and again runs (as you’d expect) with :
Hello World!
So What’s the Difference
The difference is in the evaluation vs execution order of the code. Basically :
- Declarations are always evaluated before the enclosing scope is run
- Expressions are evaluated as they are encountered.
To demonstrate what I mean, let’s flip the function definition with the call.
Declaration
var sys = require('sys'); helloWorld(); function helloWorld() { sys.puts('Hello World!'); }
Expression
var sys = require('sys'); helloWorld(); var helloWorld = function() { sys.puts('Hello World!'); }
Again, the function declaration runs as expected, but the expression gives the following error message :
TypeError: undefined is not a function.
Aha! So as you can see, function declarations are ‘floated’ to the top of their scope, so that they are guaranteed to be defined before any call to them. Whereas expressions are controlled more explicitly by the coder.
Well? .. What Does this Mean?
Now you may be thinking that this ‘safety’ feature is great, but the general rule I see in the JavaScript community is to use expressions over declarations. Expressions hold more true to JavaScript’s paradigms, whereas declarations stem from the mistaken attempt to make JavaScript look like Java when in fact they are very unlike.
Also, explicit over implicit is always a good rule by which to stick. The ‘auto’ moving of function declarations may seem all well and good, but could cause some confusion in reality. Expressions give you full control over your own code.




It’s amazing to think that HTML 4 is around thirteen years old.























