🪟 The this Keyword in JavaScript
Understanding the this keyword is essential for mastering JavaScript, as its value changes depending on how and where it is used. Let's break down its behavior in different contexts.
Global Context
Let’s start with an empty JS file. Even if there's no code, when you run the file:
- The JavaScript engine creates a Global Execution Context (GEC).
- A global object, called
windowin browsers, is created. - The
thiskeyword is initialized to refer to this global object.

Open the browser console and type:

Explanation:
In the browser, the global object is named window. All globally declared functions and variables become properties of window. The this keyword, when used in the global scope, also refers to the window object.

What Is the "Global Space"?
Any variable or function declared outside of any function or block resides in the global space. For example:

| index.js | |
|---|---|
All the following refer to the same value in the global scope:
| index.js | |
|---|---|
Summary: How Does this Work?
- In the global scope (browser):
thisrefers towindow. - In Node.js:
thisrefers to theglobalobject. - Inside an object’s method:
thisrefers to the object itself. - Inside a function (non-strict mode):
thisrefers to the global object. - Inside a function (strict mode):
thisisundefined. - Arrow functions:
thisis lexically scoped and inheritsthisfrom the parent scope. - DOM event handlers:
thisrefers to the HTML element that triggered the event.
Examples
Global Scope
Inside a Function
Inside an Object Method
Method Borrowing with call, apply, bind
Inside an Arrow Function
Tip
Arrow functions do NOT have their own this; they inherit this from where they are defined.
Nested Arrow Functions
this is inherited from its parent scope, which is the method where this refers to obj2.
this in DOM Event Handlers
Quick Reference
- By default,
thisrefers to the global object (windowin browsers,globalin Node.js). - Inside an object method,
thisrefers to the object. - In arrow functions,
thisis inherited (lexical). - In DOM event handlers,
thisis the element on which the handler is placed. - In strict mode,
thisinside functions (not called as a method) isundefined.
Tip
An empty JS file is the shortest possible JS program, since it still sets up the global context (window, this, etc.).