The Global Object & Global Environment
In this post we will learn about the global environment & the global execution context. Whenever any code runs in a JS, it runs inside an execution context. It’s an abstract concept, a wrapper where the JS code is executed and evaluated.
When we are looking at the JS program, we’re going to be looking at an execution context being created and run. Normally there is more than one execution context running during a JS program. The base execution context is the global execution context. When we talk about the word global, the thing that is accessible everywhere to everything in our code.
The global execution context creates two things for us:
- Global Object
- Special variable called — ‘this’
Now, let’s actually see it. Have created index.html file like this in any code editor:
And included an app.js file which is a blank JS file. Now I have run this index.html file in Google Chrome browser and opened the browser’s console & typed ‘this’ & pressed enter like this:
Here the JS file was loaded, the syntax parser started & realised there is nothing to parse as our JS file was empty. But because as we ran the file, JS engine started executing and the execution context was created. As we have seen above, as execution context is created, it will create 2 things from us — global object & ‘this’. So though our code was empty, JS engine decided what will be the value of this, and in this case it is the ‘window’ — The current window. Since we are running JS in the browser. So this window object is the current tab that we are on.
This is the global object inside the browser. If we use node.js this global object will be the different one. But there’s always a global object when we run JS.
Global: The code or variable aren’t inside a function is global.
Now, let’s check what will happen with some code. So have added one variable with some value assigned to it & one blank function like this:
After running this code: As we have seen execution context is created. Variable is not inside a function. When variables & functions are not inside any function in JS, those get attached to the global object.
If we type window.greet or simply greet in console, we get “Hello World!” values.
So when our variables and functions are lexically not sitting inside a function, they’re just sitting right there on a global object.
- At base level, when we are not inside a function, we have a global object that the JS engine creates for us as a part of the execution context.
- If we are running code inside a browser, the global object is the ‘window’ object. ‘this’ will be the ‘window’ object.
In the next article we will be continuing on the execution context and hoisting. Thank you!