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?
Functions stored in variables do not need function names. They are always invoked (called) using the variable name. The function above ends with a semicolon because it is a part of an executable statement.
we put the function in a variable if inside the function block we use the return method: var multiplyTwo = function (a) { return a * 2; };
Many variables store numbers and strings, like the ones above. Variables can also store other types of data, like lists, dictionaries, and Boolean values (true/false).
In Python, we can assign a function to a variable. And using that variable we can call the function as many as times we want. Thereby, increasing code reusability. Simply assign a function to the desired variable but without () i.e. just with the name of the function.
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.
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:
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.Here is an explaination:
There is a distinction between the function name and the variable the function is assigned to:
https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With