How is the global object in Node.js different from the window object in the browser?
The global
object in Node.js often gets compared to the window
object in the browser but they're not quite the same.
First, let's understand what the window object is before comparing it to the global object.
The window object
In the browser, the window
object is sometimes referred to as the global scope because any properties that exist on it can be used anywhere within your code, including any you create. This is the top-level scope of our JavaScript code.
var a = 'Global scope'; or // window.a = 'Global Scope'
const myFunc = () => {
console.log(window.a); // 'Global scope'
console.log(a); // or just leave out 'window'
};
Notice how the use of window
as a prefix to access these properties is optional but encouraged for readability.
The global object
In Node.js, the global
object is different. It doesn't refer to the global scope in the same way window
does in the browser.
In this situation, global
refers to a global namespace but it's the not top-level scope for defining and using variables / properties.
var a = 'Not the global scope';
const myFunc = () => {
console.log(global.a); // undefined
console.log(a); // Not the global scope
};
This is because the top-level scope in Node.js is the current module you are working in. So variables declared as in the example above, will be local to that module.
let and const
Using let
or const
to define a variable either in the browser will change how things work:
let a = 'Block scope';
const myFunc = () => {
console.log(window.a); // undefined
console.log(a); // 'Block scope'
};
This is due to block scoping in ES6.
Follow me on Twitter (@codebubb) for more tutorials!