Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

143
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda