gentleArt gentleArt - 1 year ago 69
Node.js Question

Why is my variable defined in the callback accessible elsewhere in my code?

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');
});'/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');


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

Answer Source


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download