When should I store a function into a variable?


I'm learning JavaScript at the moment and I don't quite understand when to write a function into a variable.

For instance, both of the following code blocks do the exact same thing in Node.js:

 var onReq = function(req, res) {



function onReq(req, res) {


Which is the best method to do according to best practices, and why?

3/8/2012 1:36:56 PM

Accepted Answer

Usually I'll only use a var funcName = function(){} when I would need to redefine the action(s) for that function later on. For example:

var foo = function(a){ return a * 2; }
var bar = foo(2);

foo = function(a){ return a / 2; }

bar = foo(bar);

Otherwise, for most purposes (assuming it's not a callback or a modifier) declaring a function "classically" is usually acceptable.

3/8/2012 1:43:40 PM

I default to the non-variable function onReq(){} version. It's not a concious decision I've made, but thinking about it brings forth these arguments:

  • It looks cleaner.
  • It is conceptually simpler: it's just a function, while the other is a function and a variable. It's a small thing, but I find it valuable none the less.
  • It assures me that onReq will always refer to that function body - one less thing to consider when reading the code. Sort of like marking a variable as final in Java.
  • Keeps me from "accidentally" replacing the function, causing unintended side effects elsewhere.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow