Part 5: “this” keyword in JS 🧐

Swati Redhu
4 min readJun 11, 2023

--

Let’s just take an empty JS file* where nothing to execute and see what happens behind the scenes.

  1. Go to Source
  2. Put debugger on and run program👩🏻‍💻
  3. GEC will be created and JS engine still created GEC and set up memory space
  4. There was nothing to setup as file was empty but it still did it’s job .🤷🏻‍♀️

Now comes new word “window” 🪟. What is that??

When you go to console and type window, you’ll see something printed, a big object which consist functions and variable which are created by JS engine, in global space .

This means you can access all these functions and variables anywhere in JS program

Same as above JS engine creates this 👈🏻 keyword

Try typing “this” in console and you’ll see something will get printed.

Right now, “this” represents “window” in global space.👏🏼

So, question here is what exactly is window? How to define that?

window is a global object which is created along with GEC.

So, to summaries whenever a JS program runs:
1. GEC is created
2. global object is created i.e window
3. this variable is created and points to global object

Why it is called “window” ?

JS not just run on browsers, it runs on server and others. So, wherever JS is running there must be JS engine . Like in chrome, it’s V8, firefox and safari have their own engines. So, all these JS engines have responsibility to create global object. In case of browsers, it is known as “window”. It’ll be different for node or wherever JS is running but there will always be global object.

So, at global level in GEC this === window. 😃

Now, you might have question: what is global space?🤔

Any code you write inside JS which is not inside a function is in global space.

Let see below example where we have variable “y” and “function z()”.

So, “y” and function z() is in global space. It will get attached to global object i.e window. But variable a inside function z() will not be in global object.

Now, how to access these?🧐

  1. use window.{variableName}
  2. directly use {variableName}
  3. use this.{variableName}

Note: Whenever we try to access any function or variable and we don’t put anything in front of it, it automatically assumes you are referring to global space.

so, all these referring to same place in memory space.

window.y === y=== this.y

Summary

So now you can figure out the value of this by following these simple rules:

  • By default, this refers to a global object, which is global in the case of NodeJS and a window object in the case of a browser
  • When a method is called as a property of an object, then this refers to the parent object

Note: * empty JS file — Shortest JS program.

⭐️Happy Coding. ⭐️

Hopefully, you learned something today! Before you go:

🚀👉 Clear your JS basics and find an amazing job

--

--

Swati Redhu

A developer attempting to learn the fundamentals and putting it here so that others could benefit from it.