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?
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:Otherwise, for most purposes (assuming it’s not a callback or a modifier) declaring a function “classically” is usually acceptable.