How global variables differ in browser and Node environments

We know that Global variables declared in JavaScript become properties of the Global object. This Global object is a Window object in the browser and a Global object in the Node environment.

Take a look at this simple code:

var name = 'jack'
console.log(this.name) // Output what?
Copy the code

Based on the above analysis, it is obvious that jack will be printed.

Let’s try it out with Chrome.That’s true.

Logically, this should be the same result in a Node environment.

Let’s try:The results seem surprising:The same code has different results in the browser and Node environments.

As you can see from the above test code, variables declared with var are properties of the Window object in the browser environment and not properties of the Global object in the Node environment.

What about let? Is it the same as var, or different?

Global variables declared with let do not become properties of the window object

JavaScript Advanced Programming makes it very clear:

Unlike the var keyword, variables declared in the global scope using let do not become properties of the Window object.

Such as:

var name = 'Matt'Insert the code slice hereconsole.log(window.name) // 'Matt'

let age = '26'
console.log(window.name) //undefined
Copy the code

We can also print the window directly:As you can see, the window object really only has variables declared with var.

conclusion

  1. Global variables declared using var are properties of the Window object in the browser environment and not properties of the Global object in the Node environment.
  2. Global variables declared using let, even if they do not become properties of the Window object in the browser environment.