imjp imjp - 1 year ago 65
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) {



function onReq(req, res) {


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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download