Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Browser vs NodeJs compatibility

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 ...

like image 316
Denis Kotov Avatar asked Mar 07 '26 03:03

Denis Kotov


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.

like image 118
Quentin Avatar answered Mar 09 '26 16:03

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!