Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

144
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda