Skip to main content

Command Palette

Search for a command to run...

Understanding the this Keyword in JavaScript

Updated
5 min read

Today in this blog I'll be covering the most important topic of JavaScript OOPS and that is this keyword... A comprehensive list of the topics is given below:

  1. What this represents

  2. this in global context

  3. this inside objects

  4. this inside functions

  5. How calling context changes this

This is one of the most exciting topic in the JavaScript OOPS.

I would highly recommend you to gather all the focus here, along with a tea/coffee :)


What this Represents

  • this represents an object on the basis of how and where it is called.

  • It can change according to the execution context.

  • I believe that for learning this code is a better approach rather than just theory, so let's do that.


this in Global Context

  • this varies significantly in browser and NodeJS, let's see how it is

Browser

  • In the browser when you do something like

    console.log(this)
    
    // vast object called window
    
  • In the browser it refers to the window object because that is the execution context where you are calling it.


NodeJS

  • In the NodeJS runtime environment when you'll run the same code
console.log(this)

// {}
  • In the NodeJS runtime environment, you get an empty object. The reason is same as previous.

Let's have a little fun, Here is a little bit of code, you have to try to guess the output

// NodeJS Environment

console.log(this)
console.log(this.name)

this.name = "Ved Pandey"

console.log(this)
console.log(this.name)

// {}
// undefined
// {name: Ved Pandey}
// Ved Pandey

Now, tell me did you guessed the same output? If yes, then you have understood the basics of this

but in case you didn't, here is a list of events that took place in this code:

  • So. first of all this is refering to the global object, which is empty right now ok?
console.log(this)
console.log(this.name)

// {}
// undefined
  • That is why the output first was an empty object and when you try to access a value inside an object that doesn't exists you get undefined . That is basic JavaScript and you already know that.
this.name = "Ved Pandey"

console.log(this)
console.log(this.name)

// {name: Ved Pandey}
// Ved Pandey
  • This time, you yourself added the property name inside that object and that is why the object had the value of name.

Was it hard? I don't think so...


Summary

Here is a comprehensive list of key takeaways from this section:

  • this refers to an object.

  • The object it is refers to depends on how and where it is called.

  • In browser this points to window object.

  • In nodejs this points to the global object.


this in Objects

Let's see how it works in the objects, so here comes the very first example:

const obj = {
  name: "Naruto Uzumaki",
  jutsu: "Rasen-Shuriken",
  mode: "Kurama Chakra Mode",
  age: 16,
  greet() {
    console.log(
      `Hi, i am \({this.name}, I am \){this.age} years old, I slay villians using \({this.jutsu} in \){this.mode}`,
    );
  },
};

obj.greet();

// ouput: Hi, i am Naruto Uzumaki, I am 16 years old, I slay villians using Rasen-Shuriken in Kurama Chakra Mode

Let's see what actually happend in this case:

  • First i declared an object with the properties name, jutsu, mode, age and a method greet.

  • So, what happens is that whenever you call a method like we did in obj.greet(), You pass the value of this to that method and yes, you guessed it right, the object which you are writing before the dot natation is the object which you are passing as this.

  • Now this can access all the properties inside that object and use it in the method.

If you understood this much of thing, then congratulations you finally understood what is this.


this in functions

this when called inside a function refers to the global object, here is a code example:

function example() {
  console.log(this)
}

example()

// <ref *1> Object [global] {
//  ...
// }

Here, you'll get the global object because this is refering to that object

But, there is an important thing to note that when you are in strict mode the value of this becomes undefined in functions.

function example() {
  "use strict"
  console.log(this)
}

example()

// undefined
  • Arrow function don't have thier own this rather they inherit it from their parents.
function jaadu() {
  console.log(this);
  const jaadu2 = () => {
    console.log(this);
  };
  jaadu2();
}
const jaadu3 = () => {
  console.log(this);
};

jaadu3();
jaadu();

// {}
// 2 times global obj
  • The reason it was empty because it inherited from global execution context which is empty, we have seen that earlier.

  • And, the reason why the second one is global is because it inherited from its parent function.


Bonus:

  • There is a keyword named globalThis which always refers to the global object no matter where it is called.
console.log(globalThis);

function jaadu() {
  console.log(globalThis);
}

const obj = {
  name: "Kira",
  death() {
    console.log('Name has been written in', globalThis);
  },
};

jaadu()
obj.death()

// 3 times global object

Wrap Up!

That was it for today guys, make sure to leave feebacks, if any doubts, you can DM me on X or ask in the comment section, I'll clear all of your doubts.

I'll catch you up soon, until then keep coding and enjoying your tea/coffee ☕💝

JavaScript: Everything you should know

Part 20 of 26

This is your ultimate guide towards JavaScirpt, this series of articles include - JavaScript Operators: The Basics You Need to Know - Understanding Variables and Data Types in JavaScript - Template Literals in JavaScript - Control Flow in JavaScript: If, Else, and Switch Explained - Array Methods You Must Know - JavaScript Arrays 101 - Function Declaration vs Function Expression: What’s the Difference? - Arrow Functions in JavaScript: A Simpler Way to Write Functions - Understanding Objects in JavaScript - Spread vs Rest Operators in JavaScript - Destructuring in JavaScript - Map and Set in JavaScript - Understanding Object-Oriented Programming in JavaScript - Understanding the this Keyword in JavaScript - The new Keyword in JavaScript - The Magic of this, call(), apply(), and bind() in JavaScript - Array Flatten in JavaScript - String Polyfills and Common Interview Methods in JavaScript - Synchronous vs Asynchronous JavaScript - Callbacks in JavaScript: Why They Exist - JavaScript Promises Explained for Beginners - Promise Methods Explained: CID Analogy - Async/Await in JavaScript: Writing Cleaner Asynchronous Code - Error Handling in JavaScript: Try, Catch, Finally - JavaScript Modules: Import and Export Explained - The Part of Events You Never See The following 26 articles and topics are covered

Up next

Maps & Sets: The Modern Way to Store Data

What are we gonna Study? Hey there folks, hope you are doing great in your life, today we are going to understand what are maps and sets in JavaScript. The following are the topics for today: What Ma

More from this blog

L

Learning Tech

61 posts

A Blog with dozens of articles on different langauges as well as frameworks, This isn't just for you to learn, i crafted it thinking that this could be my future reference as well

It covers Networking, Web Development, Mobile Developement and very soon GenAI too!