Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Build a REST API With Express Building API Routes in Express Accepting Data

When to use () [i.e. function call] inside app.use?

Compare: app.use(jsonCheck) and app.use(jsonParser())

Why is jsonParser() explicitly called but the function we defines is not? I'm really confused, conceptually, about this, so any help would be of great help, thanks!

1 Answer

Joel Kraft
STAFF
Joel Kraft
Treehouse Guest Teacher

Hi aviralkulshreshtha,

jsonParser is 3rd-party middleware from the body-parser library. Very often, 3rd-party middleware will take the form of a function that returns a middleware function. That's what's happening here, something along the lines of the following:

function thirdPartyMiddleware () {
  // set up middleware function
  // ...
  return function( req, res, next ) {
    // process req and/or res
    next();
  }
}

Then, when this function is called, the inner function is passed to app.use:

app.use( thirdPartyMiddleware() );

A function that returns another function is sometimes referred to as a closure. We have a closure workshop that looks at this a little more closely, if you're interested:

The final video of the workshop, we actually peek under the hood a 3rd-party Express middleware library!

Hope this helps!

You're the best, thanks!