//separate function
function auth(name) {
return function (req, res, next) {
if (req.isAuthenticated() && name && req.user.name === name) next();
else if (req.isAuthenticated() && !name) next();
else res.send(401);
};
}
//separate function but uses auth
app.get('/example/a', auth(), function (req, res) {
res.send('Hello from A!');
});
//separate function but uses auth
app.get('/example/b', auth('Francis'), function (req, res) {
res.send('Hello from B!');
});
but in the below code if separate function has access to another separate function will it form closure
The function auth returns is a closure over the context of the call to auth where it's created, which is why it has access to the name parameter even though auth has returned by the time the function is called. It is not a closure over anything else relevant; req, res, and next are parameters it receives, not something it closes over.
So the overall code in the question creates two closures over two separate contexts (one each for each of the two calls to auth).
That code is fine if the goal is to create a function that uses the name you're passing auth later when it's called. It's a classic use of closures.
Related: