# Understanding the this keyword in JavaScript

This is the most confusing concept in JavaScript but once we understand about this keyword it becomes easier to understand. This has a different faces at different places like when it is in global scope it is different and when it in browser it is different and but when it is in NodeJS it is an empty object.

![](https://cdn.hashnode.com/uploads/covers/6952a8da1702bb0b40b79e89/7df39191-bce5-41a4-995d-dc3524aeddcf.png align="center")

## What does this represents ?

![](https://cdn.hashnode.com/uploads/covers/6952a8da1702bb0b40b79e89/37f1dc9a-3d99-4bc6-8d47-cd75b04cb32a.png align="center")

This refers to the objects that is currently executing in the function. It just says that who is calling the function

**This is Global Context**

Here it is calling the global which is our window object.

```xml
console.log(this); // Output is window
```

**In NodeJS**

Now here it is the calling from the NodeJS so it will return an empty object.

```xml
console.log(this) // Output is an empty object
```

**This in a Object**

Here user is having a function greet and we are calling this from greet function. So, the output is the name.

![](https://cdn.hashnode.com/uploads/covers/6952a8da1702bb0b40b79e89/7e4c1133-7b5b-43be-a393-66ddba48eadf.png align="center")

```xml
const user = {
    name = "Ravi Kumar Paswan";
    greet: function(){
        console.log(this.name);
    };
};

user.greet(); // Output is Ravi Kumar Paswan
```

**This in Function**

This is regular function

![](https://cdn.hashnode.com/uploads/covers/6952a8da1702bb0b40b79e89/2868a2c3-39b9-4f91-8f12-2c7523c68375.png align="center")

```xml
function show() {
 console.log(this); 
} 

console.log(show()); // Output is window
```

This is a strict mode

```xml
"use strict"; 
function show() {
 console.log(this); 
} 

console.log(show()); // Output is undefined
```

## How calling context changes this

This depends on the that from where we are calling this. Which you can manually control this.

```xml
const object = {
    name = "Ravi Kumar Paswan";
    greet: function(){
        console.log(this.name);
    };
};

console.log(object.greet()); // Output is Ravi Kumar Paswan
```

Here we are calling name from a greet function so, it is giving the output Ravi Kumar Paswan.

```xml
const object = {
    name = "Ravi Kumar Paswan";
    greet: function(){
        console.log(this.name);
    };
};

const fn = obj.greet();
console.log(fn); // Output is undefined
```

Here we are calling greet outside the object so it cannot access. That's why it is giving the output undefined. So, we need to use the 1st example.
