« Back to home

JavaScript function syntax revisited

A commenter pointed out that my previous posting on function in JavaScript missed out some subtle differences between function as a way to create lambdas which are assigned to variables, and function as a statement which creates a function variable.

The function statement actually has one benefit: Functions defined using it are lifted to the top of the context which contains them. This means you can refer to them before you define them. So you can do this:

function outer () {
  return inner(1);

  function inner (x) {
    return x * 2;
  };
}
console.log(outer());

But you can’t do this:

var outer = function () {
  return inner(1);

  var inner = function (x) {
    return x * 2;
  };
}
console.log(outer());

Fair enough, but I’d never try to do the latter anyway. The scope of the inner var statement is the outer function block, so I’d place it at the top of that block.

Meanwhile, the downside of function statements is that you can’t use them inside if statements. So you can’t safely do something like this:

if (debug = true) {
  function log(x) {
    alert(x);
  }
} else {
  function log(x) {
    console.log(x);
  }
}
log("Starting up");

JavaScript interpreters will define the log() function differently, and often without regard to the value of the if statement. This is a pain as soon as you start writing code which needs to generate callback functions and attach them to DOM objects.

Finally, there’s no performance difference between the two styles of function declaration. So my conclusion remains the same — you might as well use the same style of function declaration everywhere, which means the ‘var’ style.