All the other answers are 100% correct, but I thought I would add an expanded/definitive list of the scopes within a Node.js application in case anybody comes across this via Google while starting off learning Node.js or JavaScript:
Global Scope
Anything declared without the var
keyword in any file will be accessible from anywhere running in the same instance of the Node server:
// foo.js
bar = 'baz';
// qux.js
console.log(bar); // prints 'baz'
Note that this is widely considered to be a bad idea, because it makes your app strongly 'coupled'– meaning that you'd have to open foo.js to work out why bar = 'baz'
in qux.js
Module Scope
Anything declared with the var
keyword at the top level (not inside a function or object, or any other block) of a node.js file is in module scope, and will be accessible from anywhere within the same file, but will not exist anywhere else:
// foo.js
var bar = 'baz';
console.log(bar); // prints 'baz'
// qux.js
console.log(bar); // prints 'undefined'
Function Scope
Anything declared using the var
keyword within a function will only be accessible from within that function, and not from anywhere else:
// foo.js
function myFunction() {
var bar = 'baz';
console.log(bar); // prints 'baz'
}
function myOtherFunction() {
console.log(bar); // prints 'undefined'
}
// qux.js
console.log(bar); // prints 'undefined'
JavaScript is function scoped. Unlike other (block scoped) languages, variables declared in a block within a function are accessible from anywhere else in that parent function. For example, this means that if you declare a new variable inside inside a loop, it's accessible outside of that loop as well, as long as you're still inside the parent function:
function myFunction() {
while (thing === true) {
var bar = 'baz';
thing = false;
}
console.log(bar); // prints 'baz'
}
Shadowing
If you 'redeclare' an existing variable, e.g. use the var
keyword with a variable name that has been used already, then the value associated with that variable name is overwritten within the scope of the new declaration:
var bar = 'foo';
console.log(bar) // prints 'foo'
function myFunction() {
var bar = 'baz';
console.log(bar);
}
myFunction(); // prints 'baz'
console.log(bar) // prints 'foo'