Understanding the window Object, Global Execution Context, and this in JavaScript
What is the window
Object?
→ In the browser, when JavaScript code runs, the JavaScript engine automatically creates a global object and in browsers, this object is called the window
.
It represents the global scope and provides access to browser APIs, such as alert()
, setTimeout()
, console
, document
, and more.
2. Global Execution Context (GEC)
When the JavaScript engine starts running code, it creates the Global Execution Context: this happens only once when the page first loads.
Two key things are created during this:
- The global object (
window
in the browser). - The
this
keyword, which points to the global object in the global scope.
So, at the global level:
console.log(this === window); // true
3. The Global Space
Anything that is not inside a function or block is considered part of the global space.
When you declare variables or functions in this space using var or a function declaration, they automatically become properties of the global object (window
).
Example:
var a = 10;
function greet() {
return "Hello!";
}
you can access above variable and function in three different ways:
console.log(a); // 10
console.log(window.a); // 10
console.log(this.a); // 10
console.log(greet()); // Hello!
console.log(window.greet()); // Hello!
console.log(this.greet()); // Hello!
4. Let and Const Are Different
It’s important to note that let
and const
do not attach variables to the window
object:
let b = 20;
const c = 30;
console.log(window.b); // undefined
console.log(window.c); // undefined
Only var
and function declarations get attached to the window
object in the global context.
Summary
- The browser creates the
window
object when a script starts running. - The global execution context also defines the this keyword to point to the window object.
- Variables/functions defined with var and function declarations in the global space are added as properties to window.
- You can access these using
window.variableName
,this.variableName
, or justvariableName
. let
andconst
do not attach to thewindow
object.