Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

142
Views
closures in express js confusing
  • i am new to js
  • I thought closure as inner function as access to variables in outer function.
  • but in the below code if separate function has access to another separate function will it form closure
//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!');
});
about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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:

  • How do JavaScript closures work? here on Stack Overflow
  • Closures are not complicated on my anemic little blog (some of the terminology in that is outdated, from back in ES3 days, but the concepts are the same)
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!