imjp imjp - 4 months ago 6
Javascript Question

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) {
res.write('Hello');
};

http.createServer(onReq).listen(3000);


and

function onReq(req, res) {
res.write('Hello');
}

http.createServer(onReq).listen(3000);




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

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.

Comments