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!

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 Express Basics Getting Started with Express Creating a Server in Express

2 Answers

James Crosslin
.a{fill-rule:evenodd;}techdegree seal-36
James Crosslin
Full Stack JavaScript Techdegree Graduate 16,880 Points

For those people who did not understand Wiktor's explanation, this has to do with a concept you may not have run across yet: closures. Closures create an instance of a function with a closed environment for tracking variables rather than needing the global scope to track them. By defining const app = express(), we create an instance (a term you may have heard when talking about objects created using a Class constructor; this functions similarly) of the Express module with it's own unique environment. If we added const app2 = express() to our app.js file, we could create another server instance that tracked its own variables and would not interfere with the app instance.

This Express basics module goes on for a long time (it took me about a week with spaced repetition of previous lessons and in-depth examination of the express and pug documentation) so if you're really very curious about closures, you can hop over to the Treehouse closures lesson to get a quick idea. It's a short course, is next in line in Fullstack Javascript after Express Basics, and you don't need to have finished this course to understand it. Hope that helps for people who are slightly confused by all this new syntax!

Wiktor Bednarz
Wiktor Bednarz
18,647 Points

With this line, you import express module into your application. That means only that your application has got access to express, but doesn't do anything with it yet.

const express = require('express');

So calling:

const app = express();

You initialize express instance in your application and assign it to a variable. This way you can work with methods provided by express. - Just take notice that this is calling a function, this function returns your express instance.

I hope that this answer was satisfactory