Question: The following is a functional express app I have which connects to my database hosted on mlab. However, **I am confused as to how my "db" variable defined in the callback to MongoClient.connect is accessible elsewhere in my code**. Is there some magic happening within the connect function that I am not seeing? Please see the comment below: 

```
const express = require('express');
const bodyParser = require('body-parser');
const MongoClient = require('mongodb').MongoClient
const app = express();

app.use(bodyParser.urlencoded({extended: true}));

MongoClient.connect('link-to-my-db', (err, database) => {
  if (err) return console.log(err);
  db = database;
  app.listen(3000, () => {
    console.log("Listening on 3000");
  });
});

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

app.post('/quotes', (req, res) => {
  // How is it possible for "db" to be accessible here even though it was defined in a separate function?
  db.collection('quotes').save(req.body, (err, result) => {
    if (err) return console.log(err);

    console.log('saved to database');
    res.redirect('/');

  })
});

```

FYI: I was following an introductory tutorial on Node. I did not magically write the code above!

Answer: 
Quoting <http://www.w3schools.com/js/js_scope.asp>:

> 
> If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable.
> 
> 
> 

This means, since the `db` variable does not have the `var` keyword in front of it, it is implicitly declared as a global variable, and is accessible from the rest of your app.
When you do not use the var/let/const declarations this is what happens:

```
var db; // declaration from below hoisted to global scope

MongoClient.connect('link-to-my-db', (err, database) => {
  if (err) return console.log(err);
  db = database;                         // the hoisted declaration, is set here
  app.listen(3000, () => {
    console.log("Listening on 3000");
  });
});

```