-2

Can someone explain to me why db is shown as undefined in the console given the following code:

function connect(){
   var db="Connected to";
  logConnection();
}

function logConnection(){
   console.log(db);   
}

connect();

This is obviously a simplified example but in reality I'm working with nodeJS and mongodb. The db variable is in reality a connection to a database on which I want to perform queries. If I can understand this in more detail, it would greatly help with my debugging.

xlm
  • 6,854
  • 14
  • 53
  • 55
LeDoc
  • 935
  • 2
  • 12
  • 24

1 Answers1

2

The variable "db" is defined in "connect", not "logConnection". Variables in JavaScript are lexically scoped, which means that what matters is the static nesting inside functions, not the dynamic relationships at runtime as one function calls another.

Pointy
  • 405,095
  • 59
  • 585
  • 614