I heard from some tutorials that defining functions inside function is bad practice.
In my case I need to reuse some code inside two nested callbacks. For example:
router.get('...', function(req, res) {
db.on('load', function(){
function doRequest() {
// Valid token required to do the request.
}
if (!validToken) {
getValidToken().then(... doRequest() ...)
}
else {
doRequest()
}
});
});
You see the function doRequest()
is defined inside other functions (callbacks). Someday in the future I may need to do something like this, but inside defined
by me function
. Is that wrong?
Do I using bad practice in this "code"? Can I make it better?
If doRequest()
is defined inside the scope of the callback, it will only exist on that scope. It's called a closure and it's useful in many situations. So if you only use this function inside this scope, it's not a problem, as you won't be duplicating content.
On the other hand, if doRequest()
performs generic functions and does not access data from the callback (without being sent as a parameter), it should be defined outside, so that it can later be reused.
In the end, it's really a matter of balancing code maintenability, performance and data access. Here's a tutorial on scopes and closures.