sreesreenu sreesreenu - 4 months ago 10
Javascript Question

var express = require('express'); var app = express(), What is express()?? is it a method or a constructor? Where does it come from

var express = require('express');
var app = express();


This is how we create an express application. But what is this 'express()'? Is it a method or a constructor? Where does it come from??

Answer

Is it a method or a constructor?

Neither; it's a function, although if you said "method" I don't think anyone would give you a hard time.

A method is a function attached to an object. In JavaScript, methods are just functions that you reference via object properties.

A constructor, in JavaScript, is a function you call via the new operator. Even though other functions may create things, we don't typically call them "constructors" to avoid confusion. Sometimes they may be "creator" or "builder" functions.

Where does it come from?

ExpressJS is a NodeJS module; express is the name of the module, and also the name we typically give to the variable we use to refer to its main function in code such as what you quoted. NodeJS provides the require function, whose job is to load modules and give you access to their exports. (You don't have to call the variable express, you can do var foo = require('express'); and use foo instead, but convention is that you'd use the module's name, or if only using one part of a module, to use the name of that part as defined by the module's documentation.)