The shortest JS Program is an empty program. When we run an empty Javascript code , a global execution context is created. The JS Engine sets up the global execution context and global memory space even though there is no code. In addition to that JS engine do something interesting, It also create window object.
How do this window object came out?
This window object is created by JS Engine which has many functions and variables. These are created in global memory space. So, we can access these variables and functions anywhere in Javascript program.
In addition to that JS Engine will also create this variable. At the global level this points to window object .
So,what is window?
Window is a global object which is created along with the global execution context.
Whenever any JS Program is run, a global execution context is created ,window object and along with the global execution context a this variable is created.
Let us now know more about global object created.
So, the global object in case of browser is called as window. Javascript not only runs on browsers. It runs on servers and a lot of other devices and places. Wherever Javascript is running, there must be a javascript engine there. Just like in chrome it is v8, Mozilla has it own. Likewise Safari, Edge has it own. So all these JS engine has the responsibility to create a global object. In case of browser it is called as window. In case of node it is called something else. Whereever you runs a Javascript, the names are different but always there is common features i.e a global object is created. Even though our file is empty JS will create a global object.
At the global level this===window is true.
As we all know, when global execution context is created, along with it global memory space is created. We can view it through developer tools in scope tab.
So, What is global memory space?
Any code which is not inside a function is in global memory space. In a simple way we can say that anything which is not inside a function is in global memory space.
function b()
{
var c=20; //Not in global memory space
}
If we debug the above code. We will see the variable and functions which are in global memory space are in windows object and not c=20 which is not in global space. So, whenever we create variable and functions in global space, these gets attached in window object.
var a=10;
function b()
{
var x=10;
}
console.log(window.a);
console.log(a);
console.log(x);
console.log(this.a);
/*
Output:
10
10
Not defined error as it is not in global
10
*/
Whenever we try to access any functions and variables in our program and if we do not put anything infront of it ,it assumes that it is in the global space.
So, we can come to a conclusion that window.a ,a and this.a all points to the window object I.e all are referring to the same place in the memory space.
Reference:@akshaymarch7
Top comments (3)
Thank you for the information
My pleasure, Juliya.
very helpful!!!