# this in JavaScript: The Actor Who Changes Roles

## What is `this` in JavaScript ?

In almost all other languages, `conditionals, loops, functions` and these basic things are almost the same. But in JavaScript, `this` is a keyword that makes JavaScript different.

`this` also exists in other languages, but in JavaScript it is used at a very high level. And after learning `this` , we can easily understand `call`, `apply`, `bind` and `new` later.

* * *

### `this` in Real World:

Just suppose `this` is an **actor**. The same actor plays different roles in different movies. Actor is same, but the role depends on the movie.

In the same way, the value of `this` is not fixed. It depends on where and how the code is run.

Or understand it like this: every person behaves different in his own area. At home different, in office different. `this` also changes according to its environment.

* * *

### `this` in the Global Context

Global context means: no function, no object, just `this` is written.

```javascript
console.log(this);
```

*   **In Browser console:** we get the `Window` object
    
*   **In Node.js:** we get an empty object `{}`
    

Code is same, but environment is different, that\`s why `this` is different.

**Small Update for Node.js:**

*   The `{}` result comes when your file is a CommonJS module (the one which uses `require`).
    
*   But if you use ES Modules (the one which uses `import`), then `this` will be `undefined` there.
    

```javascript
// CommonJS file (require)
console.log(this); // {}

// ES Module file (import)
console.log(this); // undefined
```

As we can see visually in the diagram below:

![](https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/d832b9e1-059d-4ea4-84f3-6f5a70146c56.png align="center")

* * *

## `this` Inside Objects

Inside an object, `this` points to **that same object**. It is like the object is saying "my own properties". So with `this`, we can easily access other properties of the same object from inside its method.

```javascript
const bollywoodFilm = {
    name: "Bajirao Mastani",
    lead: "Ranveer",
    introduce() {
        return `${this.lead} performs in ${this.name}`;
    },
};

console.log(bollywoodFilm.introduce());
// Output: Ranveer performs in Bajirao Mastani
```

Here `introduce()` is called by `bollywoodFilm`, so `this` = `bollywoodFilm`. That is why `this.lead` gives "Ranveer" and [`this.name`](http://this.name) gives "Bajirao Mastani".

**Easy way to Remember:** Look at the left side of the dot. `this` is calling the method.

```javascript
bollywoodFilm.introduce();
// ↑ left of the dot = bollywoodFilm = this
```

That\`s how we can easily use this anywhere **inside the object's methods**, but remember, it works properly with **regular methods**. Arrow functions are different.

![](https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/9490b057-38fa-4967-a268-e2b181c97cc6.png align="center")

* * *

## `this` **Inside Functions**

Now let's see `this` inside a normal function, which is not inside any object.

```javascript
function showThis() {
    return typeof this;
}

console.log(showThis());
// Output: object
```

Here nobody is calling the function with a dot, so `this` becomes the **global object**.

*   In Browser: `Window` object
    
*   In Node.js: Nodejs `global` object
    

#### **But using Strict Mode :**

If we write `"use strict"` inside the function, the result will be different.

```javascript
function showThisStrict() {
    "use strict";
    return typeof this;
}

console.log(showThisStrict());
// Output: undefined
```

In strict mode, JavaScript does not give the global object. `this` is just `undefined`.

Strict mode is safer, because we don't accidentally touch the global object.

#### **Quick Summary**

| **Function type** | **Value of** `this` |
| --- | --- |
| Normal function (no strict) | Global object |
| Normal function (strict mode) | `undefined` |

In a function, always check who is calling it. If nobody is calling it with a dot, then `this` is global object (or `undefined` in strict mode).

![](https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/ef36c1d4-52f2-456c-9c84-86d9682b3b6f.png align="center")

* * *

## How Calling Context Changes `this`

The most important point: `this` does not depend on where the function is **written**. It depends on **who is calling it**.

javascript

```javascript
const actor = {
    name: "Ranveer",
    bow() {
        return `${this.name} takes a bow`;
    },
};

console.log(actor.bow());
// Output: Ranveer takes a bow

const detachedBow = actor.bow;
console.log(detachedBow());
// Output: undefined takes a bow
```

In the first call, `actor` is calling `bow()`, so `this` = `actor`.

In the second call, we took the method out of the object and called it alone. Now nobody is on the left of the dot, so `this` is lost. This is called a **detached method**: the method loses its context.

![](https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/24b55546-59b3-4d36-8a41-84e2a92c42ed.png align="center")

* * *

### Quick Note:

*   **Global context:** `Window` in browser, `{}` in Node.js (CommonJS)
    
*   **Inside object method:** `this` = the object itself
    
*   **Inside normal function:** global object, or `undefined` in strict mode
    
*   **Calling context:** always check who is calling the function
    

* * *

You can find more of my work at [abdulrdeveloper.me](http://abdulrdeveloper.me)  
Read more posts at [blog.abdulrdeveloper.me](http://blog.abdulrdeveloper.me)
