JavaScript Browser vs NodeJs compatibility

Viewed 1115

I cannot get why in Browser code like this:

var gLet = 5;
alert(window.gLet); // 5 (become a property of the window object)

even thought it is old behavior works differently in Node.js:

var gVar = 5;
console.log(global.gVar); // undefined (don't become a property of the global object)

But it works like this in Node.js:

gVar = 5;
console.log(global.gVar); // 5 (become a property of the global object)

This mean that Node.js do not completely support old behavior? Just try to figure out all of it ...

1 Answers

Each module has its own scope, so when you declare a variable with var inside a module, it is scoped there and not globally.

Implicit globals still work as normal. You should activate strict mode so you don't create them.

Related