Home > Enterprise >  How does the const a = express() works exactly?
How does the const a = express() works exactly?

Time:05-09

I recently started learning Node/express. One doubt is bugging me for a couple of weeks now. I know what this does, and I've been able to get past it. But I cannot wrap my head around the logic used in the line 'const a = express()'.

express = require('express');
const a = express()

I don't think I have seen this before in javascript. In this case, express is an object or function (functions are also object in JavaScript) right? And this line is what gives the variable 'a' access to lots of important methods like 'listen' and 'get'. But doesn't the syntax here is wrong? To use the express function, we need to write like

const express = require('express');
const a = express.express()

or we need to use object destructuring to write like

const {express} = require('express');
const a = express()

CodePudding user response:

Perhaps the confusion is in assuming that the default export of the express module is something other than a function, but as others have pointed out, the default export of express is a function. Once imported, the returned value of that function is an instance of Express which is where you then have access to all those methods you mentioned.

Imagine that the definition of function express and the object it returns looks something like

class Express {
 // Implementation of Express server 
}
// You're importing this and calling the function, receiving a new instance of this class. In reality this could be a class or object for all I know. 
export default function express() {
  return new Express() 
}
  • Related