Function declarations vs. function expressions

There are few different ways to declare functions in JavaScript, but it’s never been made clear (to me anyway) which way is the best. Take these for example:

// Function declaration
function sayHello() {
    console.log('Hi there!');
}
// Function expression
var sayHello = function () {
    console.log('Yo my friend!');
};

Now, the first one declares a function when the script is loaded and parsed. This means that even if you execute a function before you declare it then it’s ok, because it’s read the whole script and knows about this function. Example:

sayHello(); // This works AOK

function sayHello() {
    console.log('Hi there!');
}

Whereas:

sayHello(); // Error - function isn't known about yet.

var sayHello = function () {
    console.log('Yo yo yo');
};

Ok, so you might think “Ok, function declarations are the way to go!” Well, creator of jQuery John Resig has a different take on it. To quote him from this article, using function expressions are better because:

  • Makes it easier to understand “functions as an object”. I’ve found that when you show new developers a function being assigned to a variable it suddenly becomes much more obvious that a function is actually an object and can be manipulated as such (and that a function can be passed as an argument to another function). Thus students are advanced along the path towards a better understanding of functional programming.
  • It enforces good semicolon habits. Traditional function declaration is the only situation in which semicolons aren’t needed (save for conditional statements and loops, naturally) and it makes it much more obvious when they’re required all the time.
  • Doesn’t have much of the baggage traditionally associated with functions and scope.

The only thing I would add to this is that using function expressions enforces a strictness to the order of your code, meaning that you’re more aware of what’s being declared and when.

If you have any more reason on whether to use one more than the other, please let me know!