0

Consider the following code snippet below

(async () => {
    const app = express();
    let test = "test string";

    app.get('/numbers', (req, res) => {
        res.send(test);
    }

    app.listen( 8000, () => {
      console.log( `server running http://localhost:8000`);
    });
)();

If I run the above code snippet, the server starts listening on localhost:8000.

How is that working?
How am I able to access test variable in my get method? Wouldn't the test variable be destroyed once the topmost function has finished executing?

Christian Fritz
  • 20,641
  • 3
  • 42
  • 71
Ankit Arora
  • 110
  • 3
  • 16
  • Why would the server _stop_ when `app` goes out of scope? – tkausl Oct 20 '21 at 18:16
  • well, You create the function's scope => app listens for port 8000 (in that scope) - what's the problem ..? – Vovan_Super Oct 20 '21 at 18:17
  • Why is the code in an async function? – Andy Oct 20 '21 at 18:18
  • @tkausl shouldn't the server stop once app goes out of scope because we are "listening" on app? – Ankit Arora Oct 20 '21 at 18:19
  • @Vovan_Super once the function finishes executing, `app` goes out of scope, right? So the server should also stop, right? – Ankit Arora Oct 20 '21 at 18:21
  • Who's `we`? `listen` is just a function. – tkausl Oct 20 '21 at 18:21
  • 1
    @AnkitArora, the `app` (block-scoped variable (rather const) You've created with `const app = express();` doesn't leave the scope created by the iife .. – Vovan_Super Oct 20 '21 at 18:22
  • @tkausl I have updated the code snippet to include a more valid example. – Ankit Arora Oct 20 '21 at 18:40
  • @Vovan_Super I have updated the code snippet to include a more valid example. – Ankit Arora Oct 20 '21 at 18:40
  • 1
    `Wouldn't the test variable be destroyed once the topmost function has finished executing?` No, the unnamed arrow function passed to `get` keeps it alive. This is just how scopes in JS work, nothing new. – tkausl Oct 20 '21 at 18:41
  • *"Wouldn't the test variable be destroyed once the topmost function has finished executing?"* No, because the functions are closures. – Felix Kling Oct 20 '21 at 18:41
  • @AnkitArora, there's another 'example' ( express server starts in a scope): https://github.com/VovanSuper/MERN-dummy/blob/main/server/index.js#L41 - .. it's how Javascript works (function creates scope -> it's not destroyed when js-vm finishes to execute that function ... – Vovan_Super Oct 20 '21 at 18:47

0 Answers0