Blog/NotesConcept

5 Ultimate Rules to master this keyword in JavaScript

Easy to understand 5 rules, that cover the behaviour of the "this" keyword in different contexts and helps you to master this keyword for any javascript interview.

Beginner

Anuj Sharma

Last Updated Feb 22, 2025


Advertisement

"This" keyword is a very important concept to understand for any JavaScript Interview. 'this' keyword behaves differently in different contexts, so it is important to understand those contexts & how to know "this" value in each context.

5 Ultimate Rules to master 'this' keyword

Here are 5 examples that cover all different behaviour of the "this" keyword in JavaScript:

Rule 1: Global Context

In the global context (outside of any function), this refers to the global object, which is the window object in a browser environment. Only var can be defined as part of the window (global object), let and const not attached to the global object (window) and remains undefined 

💡 In 'use strict' mode this doesn't map to window object and remains undefined.

var name = 'Random';
let car = 'BMW';
const city = 'jaipur';

console.log(this === window); // true
console.log(window.name); // Random

console.log(this.name, this.car, this.city); 
// Random undefined undefined

console.log(this.name, car, city); 
// Random BMW jaipur

Rule 2: Function Context

Inside a function, the value of this depends on how the function is called. If the function is called as a method of an object, this refers to the object (case 1). In case function is called in global object, this refers to the global object (case 2)

let obj = {
    name: 'Alice',
    greet: function() {
        console.log(`Hello, my name is ${this.name}`);
    }
};

// Case 1: How function called - with object context
obj.greet(); // "Hello, my name is Alice"

// Case 2: How function called - with window context, like window.globalFunc
const globalFunc = obj.greet;

/* 
 globalFunc invokes greet() in global context and as described in step 1, 
 "this" maps to windows in global context,
 Code tries to find the name in global context, but doesn't find so return undefined.
*/
globalFunc(); // "Hello, my name is"

Rule 3: Constructor Context

When a function is used as a constructor (i.e., called with the new keyword), this refers to the newly created object.

function Person(name) {
    this.name = name;
}
let alice = new Person('Alice');
console.log(alice.name); // "Alice"

Rule 4: Explicit Binding using call, apply or bind

The value of this can be explicitly set using the callapply, or bind methods.

function greet() {
    console.log(`Hello, my name is ${this.name}.`);
}
let alice = {name: 'Alice'};
greet.call(alice); // "Hello, my name is Alice."

Rule 5: Arrow Functions

Arrow functions do not have their own "this" value. Instead, they inherit this from the enclosing lexical scope means parent lexical scope. 

let obj = {
    name: 'Alice',
    greet: () => {
        console.log('Hello, my name is', this.name);
    }
};
obj.greet(); // "Hello, my name is undefined."

Advertisement

Advertisement


Share this post now:

Flaunt You Expertise/Knowledge & Help your Peers

Sharing your knowledge will strengthen your expertise on topic. Consider writing a quick Blog/Notes to help frontend folks to ace Frontend Interviews.

Other Related Blogs

What is javascript:void(0) and How it Works?

Anuj Sharma

Last Updated Jan 5, 2025

A comprehensive explanation about using javascript:void(0) in javascript. When to use javascript:void(0) and how it works with examples of using it with anchor tag.

Understand JavaScript Date Object with Examples (for JavaScript Interviews)

Anuj Sharma

Last Updated Jan 9, 2025

Go through different ways to display dates using javascript date object. It covers examples of date object usage to understand the main concepts of javascript date object.

HTTP/2 vs HTTP/1.1: What's the Key Difference?

Anuj Sharma

Last Updated Jan 29, 2025

Understand the difference between HTTP/2 vs HTTP/1.1 based on the various parameters, which helps to understand the improvement areas of HTTP/2 over HTTP 1.1

What happens when you type google.com in the browser

Anuj Sharma

Last Updated Feb 13, 2025

Details about how the browser works behind the scenes and what happens when you type google.com in the browser, starting from communication to the webpage rendering.

Promise Polyfill in JavaScript - Step by Step Explanation

Anuj Sharma

Last Updated Jan 28, 2025

An Interview-focused explanation of Promise Polyfill in JavaScript which helps to understand both Functional and ES6 custom promise implementation.

What is CORS ? Cross-Origin Resource Sharing Explained [For Interviews]

Anuj Sharma

Last Updated Dec 10, 2024

A brief explanation of Cross-Origin Resource Sharing (CORS) concept to enable client application accessing resources from cross domain and HTTP headers involved to enable resource access.

FrontendGeek
FrontendGeek

© 2024 FrontendGeek. All rights reserved