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 Nov 22, 2024


"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.

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

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."

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

Apply Polyfill in JavaScript: Step by Step Explanation (For Interview)

Anuj Sharma

Last Updated Nov 29, 2024

Understand how the apply method works in JavaScript and cover step by step-by-step explanation of the apply method polyfill in JavaScript to understand its internal implementation.

Explained Web Authorization Techniques - Session & JWT

Anuj Sharma

Last Updated Nov 24, 2024

Understand important web authorization techniques to enhance role-based authentication for any web application with popular techniques like Session & JSON Web Token (JWT)

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

Anuj Sharma

Last Updated Nov 16, 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.

Ultimate guide to REST API calls using Fetch: Machine Coding Essential

Vivek Chavan

Last Updated Sep 15, 2024

You will get a clear understanding about working with any rest api and common concepts asked during interviews

Call Polyfill in JavaScript: Step by Step Explanation (For Interviews)

Anuj Sharma

Last Updated Nov 30, 2024

A brief description of the "call" method in JavaScript and a step-by-step explanation of how to create call Polyfill in JavaScript by understanding its internal implementation.

Bind Polyfill in JavaScript: Step by Step Explanation

Ram V

Last Updated Nov 30, 2024

A concise explanation of the bind method in JavaScript, followed by a step-by-step exploration of how to create bind polyfill in JavaScript by understanding its internal implementation.

FrontendGeek
FrontendGeek

© 2024 FrontendGeek. All rights reserved